简体   繁体   中英

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?

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}

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 }
    );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM