0

在我的 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”)而不是显示错误消息?

4

1 回答 1

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());
于 2012-10-18T08:15:36.703 回答