WebApi 2.0 Routes do not match request parameters?

I just switched from AttributeRouting to WebApi 2.0 AttributeRouting and got the controller and action defined like this:

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

Request example:

GET: http://localhost/api/invites/test@foo.com

The answer I get is 200, with empty content (due to string.Empty).


This all works fine, but instead I want to change the email property as a request parameter. Therefore, I am updating 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 you request the endpoint with:

GET: http://localhost/api/invites?email=test@foo.com

The answer I get is 404:

{
"message": "No HTTP resource was found that matches the request URI 'http://localhost/api/invites?email=test@foo.com'.",
"messageDetail": "No route providing a controller name was found to match request URI 'http://localhost/api/invites?email=test@foo.com'"
}

Does anyone know why it does not match the route when the parameter is replaced with the request parameter and not the url string?


As requested, WebApiConfig is defined as follows:

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

    config.MapHttpAttributeRoutes();
}

Thanks!

+4
3

- , - ( "" (~/)). , .

public class ValuesController : ApiController
{
    [Route("~/api/values")]
    [HttpGet]
    public IHttpActionResult First(string email)
    {
        return this.Ok("first");
    }
}

[RoutePrefix("api/values")]
public class ValuesTwoController : ApiController
{
    [Route("")]
    [HttpGet]
    public IHttpActionResult Second(string email)
    {
        return this.Ok("second");
    }
}

:

GET: http://localhost/api/values?email=foo

404 :

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

, .

+3

, ( ) :

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

POST: http://localhost/api/invites/test@foo.com

, :

[Route("api/invites")]

( )

POST: http://localhost/api/invites?email=test@foo.com

edhedges: '/' '~', ,

+6

I think you need to change your route advertisement to this: [Route("~/api/invites?{email}")]

Here is the link: http://attributerouting.net/#route-constraints

+2
source

All Articles