Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Do I Support Empty RouteAttribute in Web API?

I have this class:

[RoutePrefix("api/v2/Foo")]
public class SomeController : BaseController
{
    [Route("")]
    [HttpGet]
    public async Task<HttpResponseMessage> Get(SomeEnum? param)
    {
        //...
    }
}

I want to call it via: api/v2/Foo?param=Bar but it doesn't work.

If I change the routing attribute thusly to include something in the RouteAttribute:

    [Route("SomeRoute")]
    [HttpGet]
    public async Task<HttpResponseMessage> Get(SomeEnum? param)
    {
        //...
    }

...then I can call api/v2/Foo/SomeRoute?param=Bar , but that isn't what I want.

How do I get the first circumstance to work?

EDIT: Domas Masiulis steered me toward the answer: the above scenario DOES work, it's just that a default global routing screwed things up. I solved the issue by adding a separate default routing that matched our convention...

    public static void RegisterRoutes(RouteCollection routes)
    {
        //ADDING THIS FIXED MY ISSUE
        routes.MapHttpRoute(
            name: "API Default",
            routeTemplate: "api/v2/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        //SOURCE OF THE ORIGINAL PROBLEM
        routes.MapRoute(
           "Default", // Route name
           "{controller}/{action}/{id}", // URL with parameters
           new { controller = "Administration", action = "Index", id = UrlParameter.Optional } // Parameter defaults
       );
    }
like image 981
Colin Avatar asked Jul 27 '15 18:07

Colin


People also ask

Which of the following types of routing is supported in Web API?

Web API 2 supports a new type of routing, called attribute routing. As the name implies, attribute routing uses attributes to define routes.

How do I specify a route in Web API?

The default route template for Web API is "api/{controller}/{id}". In this template, "api" is a literal path segment, and {controller} and {id} are placeholder variables. When the Web API framework receives an HTTP request, it tries to match the URI against one of the route templates in the routing table.

What is convention based routing in Web API?

What is Convention Based Routing in ASP.NET MVC? Routing is a mechanism which is used to handle the incoming requests coming from browsers and it represent the particular action rather than any static or physical files.


1 Answers

Any special conditions? Maybe something hidden in BaseController? Any custom configurations in RouteConfig?

Your given example works for me, made a quick test:

Used code:

[RoutePrefix("api/v2/Foo")]
public class SomeController : ApiController
{
    [Route("")]
    [HttpGet]
    public Task<int> Get(int param)
    {
        return Task.FromResult(2);
    }
}

Calling http://localhost:1910/api/v2/Foo?param=1 works as expected - returns 2.

like image 74
stack item Avatar answered Sep 28 '22 19:09

stack item