amesh
amesh

Reputation: 1319

Handling Wrong/Bad Routes in MVC 3

In my MVC application, the controllers are being created using spring IOC as controller factory. If the user is requesting for a wrong controller by editing the url in the browser I am displaying in the browser 'the resource is not exist' message. Instead I want to direct him to the login page of the application.

 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();
        }
    }
}

How can I redirect user to login page("/Account/Login") instead of showing error message?

Upvotes: 0

Views: 678

Answers (1)

user1736525
user1736525

Reputation: 1129

Did you try requestContext.HttpContext.Response.Redirect(url) ?

I suppose UrlHelper will also have hardcoded controller and action names, e.g.

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

But with T4MVC(http://t4mvc.codeplex.com/) you can do this:

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

Upvotes: 1

Related Questions