如何添加一个cookie为每一位旅客到我的asp.net MVC的网站? [英] How do I add a cookie for every visitor to my asp.net MVC site?

查看:87
本文介绍了如何添加一个cookie为每一位旅客到我的asp.net MVC的网站?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我与ASP.NET MVC 3,现场试验,用剃刀作为视图引擎。我需要一个cookie分配到我的网站的每一位游客。什么是最好的地方/方式做到这一点?
请详细说明,因为我在ASP.NET很新。

I'm experimenting with an ASP.NET MVC 3 site, using razor as the view-engine. I need to assign a cookie to every visitor of my site. What would be the best place/way to do this? Please elaborate, because I'm very new at ASP.NET.

推荐答案

有3种方法来实现它没有打破MVC模式:

There are 3 ways to implement it without breaking mvc pattern:

1 - 基础类与指定的行为在 OnActionExecuting / OnActionExecuted / OnResultExecuting 方法(如果这种行为必要整个网站)

1 - Base controller class with specified behaviour at OnActionExecuting / OnActionExecuted / OnResultExecuting method (if this behavior is necessary across the entire web site)

2 - 在创建指定的行为动作过滤器 OnActionExecuting / OnActionExecuted / OnResultExecuting 方法:

2 - Create action filter with specified behaviour at OnActionExecuting / OnActionExecuted / OnResultExecuting methods:

public class MyCookieSettingFilterAttribute : ActionFilterAttribute 
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        filterContext.HttpContext.Response.Cookies.Add(new HttpCookie(name, value));
    }
}

指定过滤属性为某些控制器/操作(如果这种行为的不需要所有的网站),例如:

assign filter attribute to some controllers/actions (if this behavior is not necessary for all web site), for example

[MyCookieSettingFilter]
public class MyHomeController : Controller
{
}

public class MyAccountController : Controller
{
    [MyCookieSettingFilter]
    public ActionResult Login()
    {
    }
}

3 - 在创建指定的行为动作过滤器 OnActionExecuting / OnActionExecuted / OnResultExecuting 方法,并在其注册的Global.asax - 它会为所有控制器的所有操作的工作(如果这种行为必要所有网站)

3 - Create action filter with specified behaviour at OnActionExecuting / OnActionExecuted / OnResultExecuting methods and register it at global.asax - it will work for all actions of all controllers (if this behavior is necessary for all web site)

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

我不建议使用基本控制器的方式,因为它不是全局筛选方式不易伸长。使用不同的全局过滤器提供不同的独立的全球行为。

I don't recommend to use Base Controller way, because it less extensible than Global Filter way. Use different global filters for providing different independent global behaviors.

这篇关于如何添加一个cookie为每一位旅客到我的asp.net MVC的网站?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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