简体   繁体   中英

Url parameter not mapping

I have the following method in my BlogController:

[HttpGet]
[Route("blog/search/{searchTag:string}")]
public ActionResult Search(string searchTag) {
    // Doing some search
}

I want my url to be for example blog/search/programming and this should get me to a page showing only the posts that are tagged with programming

I also have the following route:

routes.MapRoute(
    name: "BlogSearchRoute",
    url: "{controller}/{action}/{searchTag}",
    defaults: new { 
         controller = "Blog", 
         action = "Search" 
    }
);

Unfortunately my parameter doesn't map correctly and it is always null .

UPDATE
Additional information: here is my RouteConfig class:

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

            routes.MapRoute(
                name: "BlogSearchRoute",
                url: "{controller}/{action}/{searchTag}",
                defaults: new { controller = "Blog", action = "Search", searchTag = UrlParameter.Optional });

            routes.MapRoute(
                name: "BlogRoute",
                url: "{controller}/{action}/{id}/{title}",
                defaults: new { controller = "Blog", action = "Post", title = UrlParameter.Optional});

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

In your custom route, define your searchTag as optional using:

routes.MapRoute(
    name: "BlogSearchRoute",
    url: "{controller}/{action}/{searchTag}",
    defaults: new { 
         controller = "Blog", 
         action = "Search",
         searchTag = UrlParameter.Optional
    }
);

UPDATE

You should define your Default route at the bottom under all your custom routes.

我设法通过从方法中删除BlogSearchRoute[Route()]属性,并将searchTag重命名为id来使其工作

Your route parameter {searchTag:string} has an incorrect constraint type. The ":string" constraint type does not exist and you should either remove the constraint type or take one of the valid ones that can be found in route constraints documentation.

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