.NET MVC 3自定义控制器属性
这可能是天上的馅饼,但我想知道如果下可以用一个定制控制器属性来完成。
This may be pie in the sky but I'm wondering if the following could be accomplished with a custom controller attribute.
对于大多数我的控制器,我将传递名为R到控制器中的每个动作的URL参数。 R是绑在比赛中表种族ID在我的数据库。
For a majority of my controllers, I will be passing in an URL parameter called "r" to each action within the controller. "r" is tied to a race id in the races table in my database.
我想发生的是,一个控制器动作被调用的任何时候,它会自动检查的R的存在,查询数据库,以确保R属于登录用户,并设置viewbag变量称为ViewBag.RaceId等于R。
What I would like to happen is that any time a controller action is invoked, it'll automatically check for the existence of "r", query the database to make sure "r" belongs to the logged in user and set a viewbag variable called ViewBag.RaceId equal to "r".
如果任何这些条件不满足,它会重定向他们回到登录页面。
If any of those conditions aren't met, it'll redirect them back to the login page.
我试图让我的code尽可能的干燥。
I'm trying to make my code as DRY as possible.
任何指导,将大大AP preciated。
Any guidance would be greatly appreciated.
您可以编写一个自定义的授权
属性:
You could write a custom Authorize
attribute:
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var isAuthorized = base.AuthorizeCore(httpContext);
if (isAuthorized)
{
var request = httpContext.Request;
// Fetch "r" from the route data or request
var r = request.RequestContext.RouteData.Values["r"]
?? request["r"];
var currentUser = httpContext.User.Identity.Name;
if (!CheckIfRBelongsToTheCurrentLoggedInUser(currentUser, r))
{
return false;
}
}
return isAuthorized;
}
}
现在所有剩下的就是来装饰你的控制器/这个自定义属性的操作:
Now all that's left is to decorate your controllers/actions with this custom attribute:
[MyAuthorize]
public ActionResult Foo()
{
//...
}
如果你想要把东西进入ViewBag你可以暂时把它存储在 httpContext.Items
中的 AuthorizeCore
方法成功的情况下,然后覆盖 OnAuthorization
方法,以及和检查的背景下,本项目的presence。如果是present,你可以把它存储在 filterContext.Controller.ViewBag
。
And if you wanted to put something into the ViewBag you could temporarily store it in the httpContext.Items
inside the AuthorizeCore
method in case of success and then override the OnAuthorization
method as well and check for the presence of this item in the context. If it is present you could store it in the filterContext.Controller.ViewBag
.