我目前正在一个带有购物车的网站上工作,当你打开购物车页面时,它会创建一个带有ID的cookie,然后这个用户就会注册"进入数据库就好像他们注册了一样,但缺少一些信息,比如姓名,正确的用户名(而不是添加GUID)等等。所以当他们注册时,不是创建新用户,而是数据库中的这个用户得到更新,购物车中的所有内容已经与此新帐户相关联。
问题是,此ID仅在用户输入购物车所在的链接时分配,而不是任何其他网站页面。
我可以简单地将此cookie创建添加到网站中的每个页面,但不是这样,有没有办法让它在网站的任何页面中都可以使用?
以下是我用于创建cookie的Controller中的函数示例。
HttpCookie cookie = Request.Cookies.Get("UserId");
if (cookie == null)
{
string cookieValue = Guid.NewGuid().ToString();
Customer customer = new Customer();
customer.UserName = cookieValue;
if (SqlQuery.InsertGuest(customer))
{
HttpCookie userIdCookie = new HttpCookie("userId");
userIdCookie.Value = cookieValue;
userIdCookie.Expires = DateTime.Now.AddDays(90);
Response.SetCookie(userIdCookie);
}
}
我是否必须将此添加到网站的每个页面控制器?还是有替代方案吗?
答案 0 :(得分:4)
我是否必须将此添加到网站的每个页面控制器?还是有替代方案吗?
是的还有另一种选择。使用全球注册的action filter。
public class MyCookieFilter : IActionFilter
{
public void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpCookie cookie = filterContext.HttpContext.Request.Cookies.Get("UserId");
if (cookie == null)
{
string cookieValue = Guid.NewGuid().ToString();
Customer customer = new Customer();
customer.UserName = cookieValue;
if (SqlQuery.InsertGuest(customer))
{
HttpCookie userIdCookie = new HttpCookie("userId");
userIdCookie.Value = cookieValue;
userIdCookie.Expires = DateTime.Now.AddDays(90);
filterContext.HttpContext.Response.SetCookie(userIdCookie);
}
}
}
public void OnActionExecuted(ActionExecutedContext filterContext)
{
// Put anything here you want to run after the action method (or leave empty)
}
}
在FilterConfig.cs
中全局注册过滤器使其在每次操作方法调用之前和之后运行。
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new MyCookieFilter());
filters.Add(new HandleErrorAttribute());
}
}
注意:如果您需要使用依赖注入来为过滤器提供
SqlQuery
服务,则可以构建IFilterProvider
shown here来提供通过DI过滤,而不是在GlobalFilterCollection
中注册。
ASP.NET不是自己在每个请求上编写一个cookie,而是内置Anonymous Identification Module,它非常适合匿名购物车功能。