Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebApi 2.0 Routes not matching with query parameters?

I've just switched from AttributeRouting to WebApi 2.0 AttributeRouting, and have got a controller and action defined like so:

public class InvitesController : ApiController
{
    [Route("~/api/invites/{email}")]
    [HttpGet]
    [ResponseType(typeof(string))]
    public IHttpActionResult InviteByEmail(string email)
    {
        return this.Ok(string.Empty);
    }
}

Example query:

GET: http://localhost/api/invites/[email protected]

The response I receive is a 200, with empty content (due to string.Empty).


This all works fine -- but I want to change the email property to be a query parameter instead . So I update the controller to:

public class InvitesController : ApiController
{
    [Route("~/api/invites")]
    [HttpGet]
    [ResponseType(typeof(string))]
    public IHttpActionResult InviteByEmail(string email)
    {
        return this.Ok(string.Empty);
    }
}

But now when querying the endpoint with:

GET: http://localhost/api/[email protected]

The response I receive is a 404:

{
"message": "No HTTP resource was found that matches the request URI 'http://localhost/api/[email protected]'.",
"messageDetail": "No route providing a controller name was found to match request URI 'http://localhost/api/[email protected]'"
}

Does anyone know why it doesn't match the route when the parameter is swapped to a query parameter, rather than inline of the url ?


As requested, WebApiConfig is defined like so:

public static void Register(HttpConfiguration config)
{
    var jsonFormatter = config.Formatters.JsonFormatter;
    jsonFormatter.Indent = true;
    jsonFormatter.SerializerSettings.ContractResolver = new RemoveExternalContractResolver();

    config.MapHttpAttributeRoutes();
}

Thanks !

like image 234
tris Avatar asked Dec 19 '22 21:12

tris


1 Answers

I think you need to include the query parameter (along with its type) in the Route as follows:

[Route("api/invites/{email:string}")]

using it will be

POST: http://localhost/api/invites/[email protected]

Alternatively if you want to name the query parameter:

[Route("api/invites")]

using it will be (as long as you have an email parameter in your method)

POST: http://localhost/api/[email protected]

As you comment in edhedges answer: the route template cannot start with a '/' or a '~', so you can remove that from the route as above

like image 197
ry8806 Avatar answered Dec 22 '22 09:12

ry8806