如何为我的asp.net MVC网站的每个访问者添加一个cookie?
我正在尝试使用razor作为视图引擎的ASP.NET MVC 3站点。 我需要为我网站的每个访问者分配一个cookie。 最好的地方/方式是什么? 请详细说明,因为我是ASP.NET的新手。
有三种方法可以在不破坏mvc模式的情况下实现它:
1 – 在OnActionExecuting
/ OnActionExecuted
/ OnResultExecuting
方法中具有指定行为的基本控制器类(如果整个网站需要此行为)
2 – 在OnActionExecuting
/ OnActionExecuted
/ OnResultExecuting
方法中创建具有指定行为的操作filter:
public class MyCookieSettingFilterAttribute : ActionFilterAttribute { public override void OnActionExecuted(ActionExecutedContext filterContext) { filterContext.HttpContext.Response.Cookies.Add(new HttpCookie(name, value)); } }
和
例如,将filter属性分配给某些控制器/操作(如果所有网站不需要此行为)
[MyCookieSettingFilter] public class MyHomeController : Controller { }
要么
public class MyAccountController : Controller { [MyCookieSettingFilter] public ActionResult Login() { } }
3 – 在OnActionExecuting
/ OnActionExecuted
/ OnResultExecuting
方法中创建具有指定行为的操作filter并将其注册到global.asax
– 它将适用于所有控制器的所有操作(如果所有网站都需要此行为)
public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new MyCookieSettingFilterAttribute()); }
我不建议使用Base Controller方式,因为它比Global Filter方式更不易扩展。 使用不同的全局filter提供不同的独立全局行为。
无论用户第一次访问哪个页面,这都可以。 您可以使用基本控制器inheritance控制器,然后向OnActionExecuting方法添加一些信息
public class BaseController : Controller { protected override void OnActionExecuting(ActionExecutingContext context) { HttpCookie myCookie = Request.Cookies[keyOfSomeKind]; if (myCookie == null) { HttpCookie newCookie = new HttpCookie(keyOfSomeKindy, "Some message"); newCookie.Expires = DateTime.Now.AddMinutes(3); current.Response.Cookies.Add(newCookie); } base.OnActionExecuting(context); } }
您已经拥有会话和会话cookie。
但是,如果您需要为cookie编写特定值,则可以从控制器访问响应流
this.Response.Cookies.Add();
控制器内部(这不是必需的)
设置cookie应该在您的控制器中完成。 你可以这样设置一个cookie:
Response.Cookies.Add(new HttpCookie(cookieName, cookieValue));
如果您需要在视图中获取值,最好的方法是在控制器中获取它并将其粘贴到视图模型或视图状态中:
var cookie = Response.Cookies[cookieName]; ViewData["CookieInfo"] = cookie.Value;
在你看来:
@ViewData["CookieInfo"]