Argle
Argle

Reputation: 324

MVC Routing with a constant prefix

OK, I've looked everywhere I can think to look for an answer to this simple thing, but I'm not finding it. I have a simple route with a constant as part of the URL.

        routes.MapRoute(
            name: "TagNamed",
            url: "tag/{name}/X({mytag}",
            defaults: new { controller = "Tag", action = "Index" }
            );
        routes.MapRoute(
            name: "Tag",
            url: "tag/X({mytag}",
            defaults: new { controller = "Tag", action = "Index" }
            );

So far this has worked just fine for me. I can have a url like

http://localhost:64899/tag/X(foo,Q(bar))

and I get where I need to go. But as soon as there is another "X(" in the URL, I get a 404 error. This fails, for example:

http://localhost:64899/tag/X(foo,X(bar))

Any suggestions for me?

Upvotes: 1

Views: 2149

Answers (1)

Argle
Argle

Reputation: 324

While it's possible to use boilerplate text as part of the route, it seems not to be the best practice. My revised route is as follows:

        routes.MapRoute(
            name: "Tag",
            url: "tag/{tag}",
            defaults: new { controller = "Tag", action = "Index" },
            constraints: new { tag = @"X\(.+" }
            );

What I really needed to use was a constraint. With that small change, the 404 problem went away.

Upvotes: 1

Related Questions