我有一个控制器,只能在加载特定参数时才请求授权。就像参数ID为8时一样。
public class MyAuthorizeAttribute : AuthorizeAttribute { protected override bool AuthorizeCore(HttpContextBase httpContext) { if (/* Action's inputparameter ID = 8 */) { return base.AuthorizeCore(httpContext); } return true; } }
我的行动看起来像这样(不是很有趣)
[MyAuthorize] public ActionResult Protected(int id) { /* custom logic for setting the viewmodel from the id parameter */ return View(viewmodel); }
解决方法
如果id作为请求参数(GET或POST)或路由数据参数传递:
protected override bool AuthorizeCore(HttpContextBase httpContext) { // first look at routedata then at request parameter: var id = (httpContext.Request.RequestContext.RouteData.Values["id"] as string) ?? (httpContext.Request["id"] as string); if (id == "8") { return base.AuthorizeCore(httpContext); } return true; }