假设我有一个Currency
cookie,它应该是USD
或GBP
。如果有人手动将其更改为 RUB
,它将恢复为 USD
。
为此,我创建了BaseController
类来继承System.Web.MVC.Controller
,然后我项目中的每个 Controller 都会继承BaseController
,在 BaseController
构造函数中,我调用了 CheckcookieValidity()
方法。代码如下:
public class BaseController : Controller
{
public BaseController()
{
If (CheckCookieValidity() == false)
{
SetDefaultCookie();
}
}
}
public void SetDefaultCookies()
{
var curr = new HttpCookie("curr");
curr.Value = "USD";
curr.Expires = DateTime.UtcNow.AddDays(2);
HttpContext.Current.Response.Cookies.Set(curr);
}
我对此有一些问题,如果 SetDefaultCookie()
被调用,cookie 直到下一页才会改变
- 是否可以在构造函数中重定向/刷新页面?
- 这是检查 cookie 有效性的可接受方式吗?我知道这个问题可以归类为自以为是,但我需要知道是否有更好的方法来实现这一点。
任何帮助将不胜感激,对于糟糕的英语表示歉意。
回答:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
if (CheckCookiesValidity() == false) {
SetDefaultCookies();
RouteValueDictionary route = new RouteValueDictionary(new {
Controller = "Home",
Action = "Index"
});
filterContext.Result = new RedirectToRouteResult(route);
return;
}
}
最佳答案
我不知道它是否可能在 Controller 的构造函数中重定向,但这肯定似乎是个坏主意。
如果您想在操作之前继续检查每个请求的路线,那么您可能需要查看自定义操作过滤器。网上有很多对它们的引用,但是 here是couple .
关于c# - 在构造函数中重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30746053/