简体   繁体   中英

ASP.NET MVC Attribute & Conventional Routing not working

I am trying to configure routing with both Conventional & Attribute based.

If I just use the default Conventional route included with MVC everything works. but if I add this Route attribute, I get a 404.

Here is the GET request URL: http://localhost:52386/Home/SimpleSearch?searchTerms=test&dateRange=0

Here is my RouteAttributes in Code:

[RoutePrefix("Home")] 
public class HomeController : Controller
{
    [Route("SimpleSearch/{searchTerms}/{dateRange}/{page?}")]
    [HttpGet]
    public ActionResult SimpleSearch(string searchTerms, DateRangeEnum dateRange, int page = 1)
    {
       //Code here
    }

}

Also the Route Config looks like this:

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapMvcAttributeRoutes();

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

I don't see what is wrong with this RouteAttribute, but even if something is wrong with it, why doesnt it fall back onto the default Conventional Route and work?

With the attribute route definition, you explicitly specified the route pattern to be

Home/SimpleSearch/{searchTerms}/{dateRange}/{page?}

So you should try to access your action method with same url pattern.

This should work.

 http://localhost:52386/Home/SimpleSearch/test/0

and Model binder will be able to map "test" to searchTerms parameter and 0 to dateRange parameter.

Your conventional (explicitly using querystring) will not work when you have an attribute route with a different pattern

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