Search code examples
c#.netasp.net-web-apiasp.net-web-api-routing

Attribute Routing for querystring


I have below route URL:-

www.domanname.com/subroute/GetInfo?param1=somestring&param2=somestring

I have function in webapi as:-

public class HomeController : ApiController
{
    public object GetInfo(string param1,string param2)
    {}
}

To apply route:-

[RoutePrefix("subroute")]
public class HomeController : ApiController
{
    [Route("GetInfo?param1={param1:string}&param2={param2:string}")]
    public object GetInfo(string param1,string param2)
    {}
}

But after applying above URL:-

www.domanname.com/subroute/GetInfo?param1=somestring&param2=somestring

It is not able to find that URL

How can I design this particular route?


Solution

  • You need to modify the routes a bit as query string are not normally used in attribute routes. They tend to be used for inline route parameters.

    [RoutePrefix("subroute")]
    public class HomeController : ApiController {
        //Matches GET subroute/GetInfo?param1=somestring&param2=somestring
        [HttpGet]
        [Route("GetInfo")]
        public IHttpActionResult GetInfo(string param1, string param2) {
            //...
        }
    }
    

    Also

    Enabling Attribute Routing

    To enable attribute routing, call MapHttpAttributeRoutes during configuration. This extension method is defined in the System.Web.Http.HttpConfigurationExtensions class.

    using System.Web.Http;
    
    namespace WebApplication
    {
        public static class WebApiConfig
        {
            public static void Register(HttpConfiguration config)
            {
                // Web API routes
                config.MapHttpAttributeRoutes();
    
                // Other Web API configuration not shown.
            }
        }
    }
    

    Reference Attribute Routing in ASP.NET Web API 2