2

I need to create an exception that will reroute from my MVC view to a Login screen.

routes.MapMvcAttributeRoutes();
  routes.MapRoute(
    name: "Login",
    url: "{controller}/{action}/{id}",
    defaults: new {controller = "Account", action = "Login", id = UrlParameter.Optional }
  );

For some reason it can't be done in MVC when it's a javascript request.

3 Answers3

0

This is what I'm doing on my app:

int errorCode = 9999;         
if (isReroute) {
  this.Response.StatusCode = errorCode;
  Response.RedirectToRoute("Login");
  throw new System.Web.Http.HttpResponseException(
      new HttpResponseMessage(HttpStatusCode.ExpectationFailed));
}

The this.Response.StatusCode uses your routing config and redirects the page to the desired view.

JEuvin
  • 866
  • 1
  • 12
  • 31
0

In my code, I make a base controller which has initialized method which redirects to login when it's not authenticated.

you can write same thing different way and it will work.

public class BaseController :Controller
{
   protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        {
            base.Initialize(requestContext);
            Test(); check the user
        }
}

public class TestController : BaseController
{
}

In the base controller you can do code that will work on all over application.

Anirudha Gupta
  • 9,073
  • 9
  • 54
  • 79
  • 1
    Can you give me an example of how you did it. –  Mar 22 '17 at 12:54
  • 1
    How are you accessing other controllers after the base initializes? Is this a persistent check? – JEuvin Mar 22 '17 at 13:10
  • 2
    you have access to everything HttpContext, RequestContext and ControllerContext. Remember it's fire before controller's actionresult. for post-controller code you need to use ActionFilterattribute. – Anirudha Gupta Mar 22 '17 at 13:21
  • 1
    @AnirudhaGupta I'm not following, can you please write some code for this. –  Mar 23 '17 at 13:16
  • 1
    You were talking about using ActionFilterattribute. I want an example of what you are trying to do. –  Mar 23 '17 at 14:52
0

I think what @Gupta is trying to do is the following:

public class MyNewClass : MyBaseClass
{
    public MyExceptionClass() : base()
    {
        //other stuff here
    }
}

public class MyBaseClass : Controller {
  private bool isRoute;
  private bool isAuthenticated;

  MyBaseClass(){
    isReroute = MethodCheckReroute();
    isAuthenticated = MethodCheckAuth();

    if (isReroute || !isAuthenticated) {
      Response.RedirectToRoute("Login");
      throw new System.Web.Http.HttpResponseException(
      new HttpResponseMessage(HttpStatusCode.ExpectationFailed));
   }
}
JEuvin
  • 866
  • 1
  • 12
  • 31