0

In MVC 5 application, I want to accept two different kinds of request URL:

  1. http://www.myapp.com/brand/controller/action
  2. http://www.myapp.com/controller/action

Both URL should be directed to controller action.

I tried to include optional parameter brand in it, but no luck.

RouteTable.Routes.MapRoute(
    "default",
    "{brand}/{controller}/{action}",
    new { brand = UrlParameter.Optional, controller = "Home", action = "Index" });

Apparently optional parameter is not allowed before controller.

Any idea?

Jason Li
  • 1,194
  • 2
  • 11
  • 17
  • 1
    A `UrlParameter.Optional` can only be applied to the last segment. You would need 2 route definitions `{brand}/{controller}/{action}` (where `brand` is not optional) and `{controller}/{action}` but then you would need a constraint on the first route so that if `brand` is not one of a set of predefined values it would then match the 2nd route –  Apr 11 '18 at 00:23
  • What is `brand` and what are its possible values? –  Apr 11 '18 at 00:23

1 Answers1

0

Thank you for your comment, Stephen.

What I want is to inject optional parameter brand into URL, brand should be some string values, but here I want to ignore it and direct to correct controller action.

Well, I found one function that might be useful for this case:

RouteTable.Routes.MapMvcAttributeRoutes();

But the thing is I have to put Route attribute for each controller action, like:

  public class LoginController : Controller
  {
    [HttpGet]
    [Route("~/{brand}/Login")]
    [Route("~/Login")]
    public ActionResult Index()
    {
      return View();
    }
  }

Maybe I need to find some examples how to use attribute routes.

Jason Li
  • 1,194
  • 2
  • 11
  • 17