【问题标题】:Handling Wrong/Bad Routes in MVC 3在 MVC 3 中处理错误/错误的路由
【发布时间】:2012-10-18 06:45:33
【问题描述】:

在我的 MVC 应用程序中,控制器是使用 spring IOC 作为控制器工厂创建的。如果用户通过在浏览器中编辑 url 来请求错误的控制器,我将在浏览器中显示“资源不存在”消息。相反,我想将他引导到应用程序的登录页面。

 public class ControllerFactory : IControllerFactory
{
    private static readonly ILog log =
      LogManager.GetLogger(typeof(ControllerFactory));
    public IController CreateController(RequestContext requestContext, string controllerName)
    {
        log.Debug("ControllerFactory.CreateController :controllerName =" + controllerName);
        controllerName = controllerName.ToLower();
        IApplicationContext ctx = ContextRegistry.GetContext();
        Controller ControllerObj = null;

        if(ctx.ContainsLocalObject(controllerName))
        {
            ControllerObj = (Controller)ctx[controllerName];
            log.Debug("Controller Object is created :" + controllerName);
        }
        else
        {
               //Showing error message
            requestContext.HttpContext.Response.Write(String.Format("<br/><b><valign=\"center\"><Font Size=\"6\" Font Color=\"Red\"> The Resource {0} is not available</b>", controllerName));
         // **Insteadd of showing the above message I want to direct user to the login page.**
         // **"Account/Login"**
            log.Error("there is no controller defintion with " + controllerName);
            requestContext.HttpContext.Response.End();
        }
        return ControllerObj;
    }


    public SessionStateBehavior GetControllerSessionBehavior(RequestContext requestContext, string controllerName)
    {
        return SessionStateBehavior.Default;
    }

    public void ReleaseController(IController controller)
    {
        IDisposable disposable = controller as IDisposable;
        if (disposable != null)
        {
            disposable.Dispose();
        }
    }
}

如何将用户重定向到登录页面(“/Account/Login”)而不是显示错误消息?

【问题讨论】:

标签: asp.net-mvc asp.net-mvc-3 redirect routing


【解决方案1】:

你试过requestContext.HttpContext.Response.Redirect(url)吗?

我想 UrlHelper 也会有硬编码的控制器和动作名称,例如

UrlHelper url = new UrlHelper(Request.RequestContext);
var result = url.Action("Login", "Account");

但是使用 T4MVC(http://t4mvc.codeplex.com/) 你可以这样做:

var result = url.Action(MVC.Account.Login());

【讨论】:

  • 我知道我可以在一般情况下使用它。在 MVC 中相同的语法是什么?我不想使用硬编码的网址。如何使用UrlHelper.GenerateUrl()
  • 作为一般语法UrlHelper url = new UrlHelper(Request.RequestContext); String RedirectUrl = url.Action("Login", "Account"); HttpContext.Response.Redirect(RedirectUrl);
猜你喜欢
  • 1970-01-01
  • 2019-07-21
  • 1970-01-01
  • 2011-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-23
相关资源
最近更新 更多