1
votes

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 }
            );
        }
    }
3
Less precise routes should normally be last. BlogSearchRoute is never used when it is after Default route. - AndreySarafanov
Side notes: search text generally does not work as part of "path" segment of URI due to restrictions on characters allowed there; consider to specify explicit urls explicitly to minimize number of conflicts in the routing table: url: "blog/search/{searchTag}". Not directly related to your problem. - Alexei Levenkov

3 Answers

1
votes

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.

0
votes

I managed to get it working by removing BlogSearchRoute, the [Route()] attribute from my method and renaming searchTag to id

0
votes

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.