0

I have the following route:

    routes.MapRoute(
        "SetPassword",
        "Account/SetPassword/{token}",
        new { controller = "Account", action = "SetPassword" }
    );

and I want the token to be mandatory. But the problem is that if the token is missing, route falls back to the default one:

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );

What I want is to return 404 Not Found if someone enters an address like http://mysite.com/Account/SetPassword

How do I specify that the token is mandatory parameter and the routing must stop at this route if controller and action names match the specification?

1 Answer 1

1

One thing that you could do would be to put a Route Constraint on your Default Route, preventing it matching any actions in the Account Controller:

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", 
                        action = "Index", 
                            id = UrlParameter.Optional },
    constraints: new RouteValueDictionary { { "controller", "^(?!Account$).*" } }
);

Another thing that you could do would be to throw an HttpException in your action if Token was empty.

public ActionResult SetPassword(string token)
{
    if (String.IsNullOrEmpty(token))
    {
        throw new HttpException(404, "Page not found");
    }
    ViewBag.Token = token;
    return View();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.