DhavalR
DhavalR

Reputation: 1417

Attribute routing not working in MVC4

I am using Attribute Routing in MVC4 application. I have set route to [Route("test-{testParam1}-{testParam2}")]. Here `{testParam2}' may consist the word 'test'. For example, if I enter a url as below,

localhost:33333/test-temp-test-tempparam2

This gives me 404 error. Here in the url, here {testParam2} is having two words test tempparam2 formatted to test-tempparam2. When test word is at last position of {testParam2}, it runs good. That means if the url is like .../test-temp-tempParam2-test runs good. But following give error. .../test-temp-test-tempParam2.

Below is the code that may help...

[Route ("test-{testParam1}-{testParam2}")]
public ActionResult Foo (int testParam2) {...}

Now try following two url.

  1. localhost:(port)/test-temp-1

  2. localhost:(port)/test-test-temp-1

In my case second gives error. In this case first parameter is formatted to test-temp from test temp. First runs good.

How to solve this problem?

Upvotes: 5

Views: 1800

Answers (2)

ilya korover
ilya korover

Reputation: 230

Do you have the following piece of code in you Global.asax file?

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);

    routes.MapMvcAttributeRoutes();

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

Upvotes: 1

Nkosi
Nkosi

Reputation: 247561

OP indicated that the last parameter in the route template is an int

Use a route constraint.

Route constraints let you restrict how the parameters in the route template are matched. The general syntax is {parameter:constraint}. For example:

[Route ("test-{testParam1}-{testParam2:int}")]
public ActionResult Foo (int testParam2) {...}

Thus, when trying following two URLs.

localhost:(port)/test-temp-1

localhost:(port)/test-test-temp-1

The first would match route data {testParam1 = temp}-{testParam2 = 1}

And the second would match route data {testParam1 = test-temp}-{testParam2 = 1}

Upvotes: 2

Related Questions