我已经进行了自定义访问检查ActionFilterAttribute,如果他们没有足够的访问权限我想重定向到错误页面.这是我到目前为止所拥有的.
RouteValueDictionary routeValues = new RouteValueDictionary(new {
action = "Error",
controller = "Home",
error = new Error(HttpStatusCode.Unauthorized, "You do not have sufficient access to complete your request.", (HttpContext.Current != null ? HttpContext.Current.Request.UserHostAddress : ""), DateTime.Now)
});
filterContext.Result = new RedirectToRouteResult(routeValues);
Run Code Online (Sandbox Code Playgroud)
这是错误页面操作方法
public ActionResult Error(Error error)
Run Code Online (Sandbox Code Playgroud)
但是当路由重定向到action方法时,'error'参数为null,如果没有参数为null,我该怎么做?
重定向时,无法传递复杂的对象参数.您可以传递它的组成属性,并让默认模型绑定器完成重构它的工作.假设你有以下型号:
public class Error
{
public string Message { get; set; }
public HttpStatusCode Status { get; set; }
public string UserHost { get; set; }
public DateTime Date { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
你可以像这样重定向:
var routeValues = new RouteValueDictionary(new
{
action = "Error",
controller = "Home",
Message = "You do not have sufficient access to complete your request.",
Status = HttpStatusCode.Unauthorized,
// Remark: never use HttpContext.Current :
UserHost = filterContext.HttpContext.Request.UserHostAddress,
Date = DateTime.Now.ToString("u")
});
filterContext.Result = new RedirectToRouteResult(routeValues);
Run Code Online (Sandbox Code Playgroud)
另外,对于处理授权,我建议您编写自定义AuthorizeAttribute而不是自定义ActionFilterAttribute.它在语义上更正确.
| 归档时间: |
|
| 查看次数: |
2836 次 |
| 最近记录: |