【发布时间】:2013-11-26 05:49:35
【问题描述】:
我刚刚从 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);
}
}
查询示例:
GET: http://localhost/api/invites/test@foo.com
我收到的响应是 200,内容为空(由于 string.Empty)。
这一切都很好——但我想将电子邮件属性更改为查询参数。所以我将控制器更新为:
public class InvitesController : ApiController
{
[Route("~/api/invites")]
[HttpGet]
[ResponseType(typeof(string))]
public IHttpActionResult InviteByEmail(string email)
{
return this.Ok(string.Empty);
}
}
但是现在查询端点时:
GET: http://localhost/api/invites?email=test@foo.com
我收到的响应是 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'"
}
有谁知道为什么当参数被交换为查询参数而不是内联url时它与路由不匹配?
根据要求,WebApiConfig 定义如下:
public static void Register(HttpConfiguration config)
{
var jsonFormatter = config.Formatters.JsonFormatter;
jsonFormatter.Indent = true;
jsonFormatter.SerializerSettings.ContractResolver = new RemoveExternalContractResolver();
config.MapHttpAttributeRoutes();
}
谢谢!
【问题讨论】:
-
您并没有真正明确您的意图(您正在尝试做什么)您正在使用 POST,您实际上是在请求正文中发布任何信息吗?还是这种方法真的是 GET?
-
抱歉,当电子邮件通过查询参数传递时,切换到 HttpGet 对 404 没有任何影响。我会更新问题。
-
我刚刚尝试了您的方案,但无法重现。您能分享一下您的 WebApiConfig.cs 的样子吗?
-
添加到问题的末尾。
-
好的 - 我想我明白了。这似乎与我定义的另一条路线发生冲突。如果我将 Route 定义更改为“~/api/invites/create”,并使用 /api/invites/create?email=test@foo.com 调用它,它似乎工作正常。至于它与哪个端点发生冲突,我将不得不更深入地挖掘。那里的响应更清晰一点会很好:(
标签: c# asp.net-web-api asp.net-web-api-routing