Asp.net mvc 3 在MVC 3中获取authorized属性中的模型数据
我正在用authorized属性装饰我的控制器操作Asp.net mvc 3 在MVC 3中获取authorized属性中的模型数据,asp.net-mvc-3,action-filter,Asp.net Mvc 3,Action Filter,我正在用authorized属性装饰我的控制器操作 [ServiceAuthorize(Roles="Editor,Publisher,Administrator")] public JsonResult Create(NewsArticle newsArticle) 我的NewsArticle模型中有一个字段,我想在authorize属性中的OnAuthorize方法中使用该字段 [ServiceAuthorize(Roles="Editor,Publisher,Administrator"
[ServiceAuthorize(Roles="Editor,Publisher,Administrator")]
public JsonResult Create(NewsArticle newsArticle)
我的NewsArticle模型中有一个字段,我想在authorize属性中的OnAuthorize方法中使用该字段
[ServiceAuthorize(Roles="Editor,Publisher,Administrator")]
public JsonResult Create(NewsArticle newsArticle)
是否有任何方法可以从AuthorizeAttribute的OnAuthorize方法中获取模型
我以为它会在授权上下文中的某个地方可用,但我找不到它。我知道我可以在过滤器属性的ActionExecutingContext中找到它,但这意味着我需要在我的操作上使用另一个过滤器,并且我希望能够在一个步骤中执行所有授权
谢谢
有没有办法从OnAuthorize中获取模型
属性的方法
否,因为OnAuthorization在模型绑定器之前运行。您可以做的是从值提供程序读取值:
public override void OnAuthorization(AuthorizationContext filterContext)
{
var value = filterContext.Controller.ValueProvider.GetValue("someproperty");
...
}
我试图完成同样的事情,基本上希望通过action方法参数上的属性来控制授权,例如:
[MyAuthorize]
public ActionResult MyAction(
[Require(Permission.Write)] MyCustomObject arg1,
[Require(Permission.Read)] MyCustomObject arg2
) {
// ... all authorization would be handled before the action is invoked ...
}
class MyAuthorize : AuthorizeAttribute {
public override void OnAuthorization(AuthorizationContext filterContext) {
// ... filterContext doesn't have the argument objects ...
}
}
当重写AuthorzeAttribute.OnAuthorization(…)
时,我遇到了同样的问题,模型绑定的参数还不存在。为了完成我所需要的,我实现了IActionFilter
,它公开了一个方法OnActionExecuting
,该方法将在绑定模型之后调用,但在调用操作之前调用。我的原型实现如下所示:
class MyAuthorizeAttribute : AuthorizeAttribute, IActionFilter {
public override void OnAuthorization(AuthorizationContext filterContext) {
// ... I guesss this isn't really needed any more.
// the auth check is handled in OnActionExecuting.
}
void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext) {
}
void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext) {
foreach (var param in filterContext.ActionDescriptor.GetParameters()) {
var attr = (RequireAttribute)param.GetCustomAttributes(typeof(RequireAttribute), false).FirstOrDefault();
if(attr != null) {
Object obj;
if (filterContext.ActionParameters.TryGetValue(param.ParameterName, out obj)) {
var sec = obj as ISecurable;
if (sec == null || !sec.HasPermission(filterContext.RequestContext, attr.Permission)) {
filterContext.Result = new HttpStatusCodeResult(System.Net.HttpStatusCode.Unauthorized);
}
}
}
}
}
}
interface ISecurable {
bool HasPermission(Permission permission);
}
这只是我正在从事的一个项目的概念证明,但似乎是一个可行的解决方案 谢谢你,达林。我假设“someproperty”在我的例子中可能是“newarticle”?“我会查清楚的。”佩里,不,你想错了。它将是您感兴趣的
新闻文章
类的属性。正如我所说的,由于OnAuthorization
方法在模型绑定器之前运行,因此在这个阶段不能真正讨论新闻文章的实例。您可以查看ValueProvider所做的请求值。当然,在这个阶段,它们将以弦的形式出现。您可能还需要进行一些额外的解析。感谢您的澄清。这非常有效。是的,我可以获得原始值,然后根据需要进行转换以获得所需的内容。在本例中,我需要的是一个字符串,以便使用AttemptedValue。