【问题标题】:ASP.NET Web Api 2 routing issueASP.NET Web Api 2 路由问题
【发布时间】:2017-10-08 20:08:10
【问题描述】:

我真的不明白为什么它不起作用。我有以下代码:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

[RoutePrefix("api/Profile")]
[System.Web.Http.AuthorizeAttribute]
[IdentityBasicAuthenticationAttribute]
public class ProfileApiController : ApiController
{
    [HttpPost]
    [ValidateApiContentLength]
    [ValidateApiMimeMultipart]
    [Route("Upload")]
    public async Task<HttpResponseMessage> UploadDocumentAsync(string description)
    {
       //....
    }
}

}

但是当我打电话时:http://localhost:11015/api/profile/Upload

我收到 404 错误:

{
    "Message": "No HTTP resource was found that matches the request URI 'http://localhost:11015/api/profile/Upload'.",
    "MessageDetail": "No action was found on the controller 'ProfileApi' that matches the request."
}

但洞察力说的是错误:

什么是不正确的?

【问题讨论】:

  • 1.你是怎么打电话的? 2.你在项目中使用的是哪个模板:asp mvc还是asp mvc web api?

标签: asp.net-web-api asp.net-web-api2 asp.net-web-api-routing


【解决方案1】:

WebApi 路由找不到您的 UploadDocumentAsync 方法。在您的应用程序中,您同时使用路由表(在 WebApiConfig 类中)和属性路由。你不需要后者。

您可以保留 WebApiConfig 类中的路由表并删除 Route 和 RoutePrefix 属性。

将 Profile 控制器中的 UploadDocumentAsync 操作更改为:

...
[HttpPost]
public async Task<HttpResponseMessage> UploadUploadDocumentAsync(string description)
{
...

只留下 HttpPost 属性。

您可以通过调用来访问您的资源(例如,您可以通过 Fiddler 进行):

发布http://localhost:11015/api/profile/

更新:

或者,如果您真的想在您的 url 中包含“上传”部分,您可以利用 Route 属性来执行操作:

[Route("api/profile/upload")]

【讨论】:

  • 首先:OP 想要使用属性路由,并询问为什么属性路由不起作用。因此,您建议不要使用属性路由并不能回答问题,其次:[Route("api/profile/upload")] 也在改变 OP 设计路由的方式,因此,这两个建议都建议更改设计,因此不回答问题。
  • 首先:OP 没有准确地询问 attribute 路由,也许表路由就足够了。第二: api/profile/upload 将允许他使用如下网址:http(s)://{host}/api/profile/upload OP想要什么。
  • @CodingYoshi,早上重新阅读了这个问题,我想你可能是对的。 OlegSh,如果是这样,请让我们。
  • @serge.karalenka ,[Route("api/profile/upload")] 根本不起作用...似乎,路由是正确的,因为 App Insight 说的是异常。但为什么它不起作用?
【解决方案2】:

我找到了解决办法。问题不在路由中。问题出在行动参数上。它不应该用于 POST 方法。其他的保持原样

    [HttpPost]
    [ValidateApiContentLength]
    [ValidateApiMimeMultipart]
    [Route("upload")]
    public async Task<HttpResponseMessage> UploadDocumentAsync()
    {

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-25
    • 1970-01-01
    • 1970-01-01
    • 2014-11-27
    相关资源
    最近更新 更多