Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
431 views
in Technique[技术] by (71.8m points)

asp.net mvc - Run a method in each request in MVC, C#?

In WebForm we could write a method in MasterPage.cs and it ran in each request .
e.g:

MasterPage.cs
--------------
protected void Page_Load(object sender, EventArgs e)
{
   CheckCookie();
}

How can we do something like this in MVC ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In ASP.NET MVC you could write a custom global action filter.


UPDATE:

As requested in the comments section here's an example of how such filter might look like:

public class MyActionFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var fooCookie = filterContext.HttpContext.Request.Cookies["foo"];
        // TODO: do something with the foo cookie
    }
}

If you want to perform authorization based on the value of the cookie, it would be more correct to implement the IAuthorizationFilter interface:

public class MyActionFilterAttribute : FilterAttribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationContext filterContext)
    {
        var fooCookie = filterContext.HttpContext.Request.Cookies["foo"];

        if (fooCookie == null || fooCookie.Value != "foo bar")
        {
            filterContext.Result = new HttpUnauthorizedResult();
        }
    }
}

If you want this action filter to run on each request for each controller action you could register it as a global action filter in your global.asax in the RegisterGlobalFilters method:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new HandleErrorAttribute());
    filters.Add(new MyActionFilterAttribute());
}

And if you need this to execute only for particular actions or controllers simply decorate them with this attribute:

[MyActionFilter]
public ActionResult SomeAction()
{
    ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...