我一直在努力寻找如何编写自定义属性来验证方法参数的示例,即转换此表单:
public void DoSomething(Client client)
{
if (client.HasAction("do_something"))
{
// ...
}
else
{
throw new RequiredActionException(client, "do_something");
}
}
Run Code Online (Sandbox Code Playgroud)
进入这个:
public void DoSomething([RequiredAction(Action="some_action")] Client client)
{
// ...
}
Run Code Online (Sandbox Code Playgroud)
据我所知,我需要将此属性添加到我的自定义属性,但我对如何访问修饰参数感到茫然Client:
[AttributeUsageAttribute(AttributeTargets.Parameter)]
public class RequireActionAttribute : System.Attribute
{
public Type Action {get; set;}
public RequireActionAttribute()
{
// .. How do you access the decorated parameter?
Client client = ???
if (!client.HasAction(Action))
{
throw new RequiredActionException(client, Action);
}
}
}
Run Code Online (Sandbox Code Playgroud) 就像我可以用来存储一些必要信息的标签?但HTML确实不需要或使用它?像Visual Basic上的对象的标记属性一样工作?
这可能是一个新手问题但是;
假设我有一个ActionResult,我只想在下班后授予访问权限.
我们还要说我想用自定义属性装饰我的ActionResult.
所以代码可能看起来像;
[AllowAccess(after="17:00:00", before="08:00:00")]
public ActionResult AfterHoursPage()
{
//Do something not so interesting here;
return View();
}
Run Code Online (Sandbox Code Playgroud)
如何准确地我会得到这个工作?
我已经做过一些关于创建自定义属性的研究,但我想我对如何使用它们缺乏了解.
请假设我对创建和使用它们几乎一无所知.
我需要在我使用Html.ActionLink()构建的锚上放置一个自定义属性
<%: Html.ActionLink("Delete", "Delete", new { id = Model.ID }, new { data-icon = "ui-icon-trash" })%>
Run Code Online (Sandbox Code Playgroud)
使用正确的"data-"前缀,根据http://www.w3.org/TR/html5/elements.html#attr-data,我从Visual Studio得到以下错误.
无效的匿名类型成员声明符.必须使用成员分配,简单名称或成员访问声明匿名类型成员.
由于我不能在匿名类型中使用连字符,因此添加自定义HTML属性的最佳方法是什么?
我写了一个有点通用的反序列化机制,它允许我从C++应用程序使用的二进制文件格式构造对象.
为了保持清洁和易于更改,我创建了一个Field扩展的类,Attribute构造Field(int offset, string type, int length, int padding)并应用于我希望反序列化的类属性.这是它的样子:
[Field(0x04, "int")]
public int ID = 0;
[Field(0x08, "string", 0x48)]
public string Name = "0";
[Field(0x6C, "byte", 3)]
public byte[] Color = { 0, 0, 0 };
[Field(0x70, "int")]
public int BackgroundSoundEffect = 0;
[Field(0x74, "byte", 3)]
public byte[] BackgroundColor = { 0, 0, 0 };
[Field(0x78, "byte", 3)]
public byte[] BackgroundLightPower = { 0, 0, 0 };
[Field(0x7C, "float", 3)]
public float[] BackgroundLightAngle = …Run Code Online (Sandbox Code Playgroud) 我想保护控制器操作,以便只有角色为"Admin"的用户可以进入.
我不使用角色/成员资格提供程序,一切都是自定义的.
到目前为止我这样做了:
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var isAuthorized = base.AuthorizeCore(httpContext);
if (!isAuthorized)
return false;
string username = httpContext.User.Identity.Name;
UserRepository repo = new UserRepository();
return repo.IsUserInRole(username, "Admin");
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,我在这里硬编码了"Admin".
我希望这是动态的.
这项工作现在:
[CustomAuthorize]
public ActionResult RestrictedArea()...
Run Code Online (Sandbox Code Playgroud)
但是我想要这样的东西:
[CustomAuthorize(Roles = "Admin")]
public ActionResult RestrictedArea()
Run Code Online (Sandbox Code Playgroud) 我正在用C#编写ReSharper 8.0和VS2012 for .Net 4.0.
ReSharper包含一个属性:JetBrains.Annotations.PureAttribute.这用于提供检查"不使用纯方法的返回值".
代码约定包括一个属性:System.Diagnostics.Contracts.PureAttribute.代码合同检查使用它来确保调用不会产生可见的状态更改,因此不需要重新检查对象的状态.
目前,为了获得这两种工具的功能,需要使用每个属性的方法对方法进行注释.更糟糕的是,因为它们都共享相同的类型名称,所以您需要限定每个属性.
[Pure]
[Jetbrains.Annotations.Pure]
public bool isFinished() {
...
Run Code Online (Sandbox Code Playgroud)
为避免这种情况,应该有三种方法:
这些都有可能吗?
我有一个自定义属性,我想限制为返回类型为void的方法.
我知道我可以限制使用方法,[AttributeUsage(AttributeTargets.Method)]但似乎没有办法限制返回类型或方法签名的任何其他方面.
该[System.Diagnostics.Conditional]属性完全具有我想要的限制.将其添加到非void方法会导致编译器错误:
Conditional属性在'(SomeMethod)'上无效,因为它的返回类型不是void
和IntelliSense说:
属性'System.Diagnostics.ConditionalAttribute'仅对具有'void'返回类型的属性类或方法有效.
如果我F12到了,ConditionalAttribute我看到它装饰有以下属性:
[Serializable]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method,AllowMultiple = true)]
[ComVisible(true)]
其中没有任何关于返回类型的说明.
如何为Conditional属性完成,我可以为自定义属性执行相同的操作吗?
我正在寻找一种方法,以可配置的方式使用SwashBuckle在Swagger文档中显示/隐藏WebAPI路由.添加[ApiExplorerSettings(IgnoreApi = true)]确实会隐藏路由,但每次我想要更改时我都需要重新编译.
我已经研究过创建一个IOperationFilter使用我定义的自定义属性的方法.这样我可以用a装饰路线[SwaggerTag("MobileOnly")]并检查web.config或其他东西,看看是否应该显示路线.属性定义如下:
public class SwaggerTagAttribute : Attribute
{
public string[] Tags { get; private set; }
public SwaggerTagAttribute(params string[] tags)
{
this.Tags = tags;
}
}
Run Code Online (Sandbox Code Playgroud)
所述IOperationFilter检测所述属性被定义并且IDocumentFilter去除的路径在这里被定义:
public class RemoveTaggedOperationsFilter : IOperationFilter, IDocumentFilter
{
private List<string> TagsToHide;
public RemoveTaggedOperationsFilter()
{
TagsToHide = ConfigurationManager.AppSettings["TagsToHide"].Split(',').ToList();
}
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
var tags = apiDescription.ActionDescriptor
.GetCustomAttributes<SwaggerTagAttribute>()
.Select(t => t.Tags)
.FirstOrDefault();
if (tags != null && TagsToHide.Intersect(tags).Any()) …Run Code Online (Sandbox Code Playgroud) 我有一个评估字段的异步方法。
Task<bool> MyMethod(object obj);
Run Code Online (Sandbox Code Playgroud)
我想创建一个使用上述方法的自定义验证属性。我的问题是该类ValidationAttribute不支持异步方法。
我通常重写以下方法:
ValidationResult IsValid (object? obj, ValidationContext validationContext);
Run Code Online (Sandbox Code Playgroud)
但我的异步方法的输出是Task<ValidationResult>,我不想使用同步方法。
您有解决方案或建议吗?
提示:由于I/O阻塞,我想使用异步方法。(没有 CPU 限制或繁重的操作。)
c# ×7
asp.net-mvc ×3
.net ×1
asp.net ×1
asp.net-core ×1
asynchronous ×1
attributes ×1
decorator ×1
generics ×1
html ×1
html5 ×1
postsharp ×1
resharper ×1
swagger ×1
swashbuckle ×1