MR.ABC
MR.ABC

Reputation: 4862

MVC Routing constrain random a-zA-Z

I like to create register a route like these:

User/{^[a-zA-Z]+$}/{controller}/{action}/{id}

That's how the URL should look like :

/User/myUser/Product/Action

So i register a route in the AreaRegistration. The constraint should only allow words.

context.MapRoute(
    "Customer_Default",
    "User/{^[a-zA-Z]+$}/{controller}/{action}/{id}",
    new { action = "Index", id = UrlParameter.Optional }
);
  1. Is my constraint correct.
  2. How redirect to this with RedirectToAction route?
  3. What is the best way to get the username in the Action? Regex...?

Upvotes: 0

Views: 73

Answers (2)

MudOnTire
MudOnTire

Reputation: 506

  1. I think the right way to use constraint is: routes.MapRoute(name: "Customer_Default", url: "User/{username}/{controller}/{action}/{id}", defaults: new { action = "Index", id = UrlParameter.Optional }, constraints: new { username = "^[a-zA-Z]+$" });
  2. I don't know how to redirect to this route..
  3. I think you'd better create a login model, and use consistent type to pass username and password.

Upvotes: 0

ediblecode
ediblecode

Reputation: 11971

You need to utilise the constraints parameter of MapRoute()

context.MapRoute(
    "Customer_Default",
    "User/{username}/{controller}/{action}/{id}",
    new { action = "Index", id = UrlParameter.Optional },
    constraints: new { username= @"^[a-zA-Z]+$" }
);

Then your action would be like so:

public ActionResult ActionName(string username, int id)

Upvotes: 1

Related Questions