WebApi 2.0路由与查询参数不匹配?

tri*_*ris 4 c# asp.net-web-api asp.net-web-api-routing

我刚刚从AttributeRouting切换到WebApi 2.0 AttributeRouting,并且有一个控制器和动作定义如下:

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

示例查询:

GET: http://localhost/api/invites/test@foo.com
Run Code Online (Sandbox Code Playgroud)

我收到的响应是200,内容为空(由于string.Empty).


这一切都很好 - 但我想将email属性更改为查询参数.所以我将控制器更新为:

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

但现在在查询端点时:

GET: http://localhost/api/invites?email=test@foo.com
Run Code Online (Sandbox Code Playgroud)

我收到的回复是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'"
}
Run Code Online (Sandbox Code Playgroud)

有人知道为什么它与参数交换到查询参数时的路由不匹配,而不是内联网址?


根据要求,WebApiConfig的定义如下:

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

    config.MapHttpAttributeRoutes();
}
Run Code Online (Sandbox Code Playgroud)

谢谢 !

ry8*_*806 6

我认为您需要在Route中包含查询参数(及其类型),如下所示:

[Route("api/invites/{email:string}")]
Run Code Online (Sandbox Code Playgroud)

使用它将是

POST: http://localhost/api/invites/test@foo.com
Run Code Online (Sandbox Code Playgroud)

或者,如果要为查询参数命名:

[Route("api/invites")]
Run Code Online (Sandbox Code Playgroud)

使用它将(只要你的方法中有一个电子邮件参数)

POST: http://localhost/api/invites?email=test@foo.com
Run Code Online (Sandbox Code Playgroud)

当您在edhedges中回答时:路径模板不能以'/'或'〜'开头,因此您可以从路径中删除它,如上所述