c# - 在构造函数中重定向

标签 c# asp.net-mvc

假设我有一个Currency cookie,它应该是USDGBP。如果有人手动将其更改为 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 直到下一页才会改变

  1. 是否可以在构造函数中重定向/刷新页面?
  2. 这是检查 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 的构造函数中重定向,但这肯定似乎是个坏主意。

如果您想在操作之前继续检查每个请求的路线,那么您可能需要查看自定义操作过滤器。网上有很多对它们的引用,但是 herecouple .

关于c# - 在构造函数中重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30746053/

相关文章:

C# 如何在使用 asp.net mvc 时设置 autopostback 属性?

c# - 如何通过显示文本在 ASP.NET 下拉列表中设置所选项目?

c# - 字典中的字符未正确转义

C#:背景色问题

html - 在 ASP.NET MVC 中处理可变数量的动态输入字段?

asp.net-mvc - 如何在MVC4中隐藏URL参数

c# - 获取 .NET 类中的枚举类型

c# - IEnumerable<T>.Reverse 是如何工作的?

c# - 以 PNG 格式保存图像时出现 GDI+ 异常

asp.net-mvc - Cookie、 session 、数据库