在 MVC、C# 中的每个请求中运行一个方法? [英] Run a method in each request in MVC, C#?

查看:11
本文介绍了在 MVC、C# 中的每个请求中运行一个方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 WebForm 中,我们可以在 MasterPage.cs 中编写一个方法,它会在每个请求中运行.
例如:

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();
}

我们如何在 MVC 中做这样的事情?

How can we do something like this in MVC ?

推荐答案

在 ASP.NET MVC 中,您可以编写一个 自定义全局操作过滤器.

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

更新:

根据评论部分的要求,这里有一个示例,说明此类过滤器的外观:

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
    }
}

如果要根据cookie的值进行授权,实现IAuthorizationFilter 接口:

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();
        }
    }
}

如果您希望此操作过滤器在每个控制器操作的每个请求上运行,您可以在 RegisterGlobalFilters 方法中的 global.asax 中将其注册为全局操作过滤器:

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()
{
    ...
}

这篇关于在 MVC、C# 中的每个请求中运行一个方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆