授权失败时更改 ModelState
Changing ModelState when authorization fails
我写了一个自定义授权过滤器:
public class MyAuthenticationAttribute : FilterAttribute, IAuthorizationFilter{
// Do the authorization
if (!isAuthenticated)
{
filterContext.Result = new HttpUnauthorizedResult();
}
}
这个过滤器有各种条件,如果用户未被授权,最终将结果设置为Unauthorized
,如果用户被授权,则什么都不做。
它正在 SPA 应用程序中使用,几乎我所有的方法都是从网格中调用的。在那些网格中,我有自定义错误处理程序,如果出现问题,它将显示友好的通知。所有错误都添加到 ModelState
.
现在,我想管理未经授权的行为并更改 ModelState
当用户无权执行例如删除操作时。
请指导我应该如何实现它以及我需要覆盖哪些方法。
更新
我可以用这条线改变模型状态:
filterContext.Controller.ViewData.ModelState.AddModelError("", "GO AWAY!");
但它 return 对用户没有任何影响。我试过使用 IAuthenticationFilter
并在挑战方法中添加 ModelState
错误,但它也没有用。
我想如果我可以 return 一些 Json
数据就可以了。
我需要以某种方式获得此操作方法的类似行为:
public ActionResult Delete([DataSourceRequest] DataSourceRequest request, object model)
{
ModelState.AddModelError("", "error");
return Json(new[] { model}.ToDataSourceResult(request, ModelState));
}
可能吗?您对实施此授权和 returning Json
数据有什么建议吗?
您可以 return 使用 context.Result
得到任何您想要的结果,在我的例子中,我想取消 Kendo 网格的更改并添加一个模型状态错误,我用此代码:
public void OnAuthenticationChallenge(AuthenticationChallengeContext context)
{
if (context.Result == null || context.Result is HttpUnauthorizedResult)
{
var ModelState = context.Controller.ViewData.ModelState;
context.Result = new JsonResult
{
Data = new Kendo.Mvc.UI.DataSourceResult
{
Errors = ModelState.SerializeErrors()
}
};
}
}
我写了一个自定义授权过滤器:
public class MyAuthenticationAttribute : FilterAttribute, IAuthorizationFilter{
// Do the authorization
if (!isAuthenticated)
{
filterContext.Result = new HttpUnauthorizedResult();
}
}
这个过滤器有各种条件,如果用户未被授权,最终将结果设置为Unauthorized
,如果用户被授权,则什么都不做。
它正在 SPA 应用程序中使用,几乎我所有的方法都是从网格中调用的。在那些网格中,我有自定义错误处理程序,如果出现问题,它将显示友好的通知。所有错误都添加到 ModelState
.
现在,我想管理未经授权的行为并更改 ModelState
当用户无权执行例如删除操作时。
请指导我应该如何实现它以及我需要覆盖哪些方法。
更新
我可以用这条线改变模型状态:
filterContext.Controller.ViewData.ModelState.AddModelError("", "GO AWAY!");
但它 return 对用户没有任何影响。我试过使用 IAuthenticationFilter
并在挑战方法中添加 ModelState
错误,但它也没有用。
我想如果我可以 return 一些 Json
数据就可以了。
我需要以某种方式获得此操作方法的类似行为:
public ActionResult Delete([DataSourceRequest] DataSourceRequest request, object model)
{
ModelState.AddModelError("", "error");
return Json(new[] { model}.ToDataSourceResult(request, ModelState));
}
可能吗?您对实施此授权和 returning Json
数据有什么建议吗?
您可以 return 使用 context.Result
得到任何您想要的结果,在我的例子中,我想取消 Kendo 网格的更改并添加一个模型状态错误,我用此代码:
public void OnAuthenticationChallenge(AuthenticationChallengeContext context)
{
if (context.Result == null || context.Result is HttpUnauthorizedResult)
{
var ModelState = context.Controller.ViewData.ModelState;
context.Result = new JsonResult
{
Data = new Kendo.Mvc.UI.DataSourceResult
{
Errors = ModelState.SerializeErrors()
}
};
}
}