【问题标题】:Web API One action works while a nearly identical one doesn't?Web API 一项操作有效,而几乎相同的操作无效?
【发布时间】:2019-03-29 17:37:13
【问题描述】:

错误信息

{
    "Message": "No HTTP resource was found that matches the request URI 'https://localhost:44390/api/UserRoutes?effectiveDate=3/29/2019'.",
    "MessageDetail": "No type was found that matches the controller named 'UserRoutes'."
}

工作行动

public class AdvanceOrderApiController : BaseApiController
{
    [HttpGet, Route("api/AdvanceOrders")]
    public AdvanceOrdersResult GetAdvanceOrdersForRouteDate(string route, DateTime effectiveDate)
    {
        ...
    }
}

// JavaScript Usage: route="0100" and effectiveDate="03/29/2019".
API.SendRequest("/api/AdvanceOrders", "GET", { route: route, effectiveDate: effectiveDate }, success, failure);

无效操作

public class UserApiController : BaseApiController
{
    [HttpGet, Route("api/UserRoutes")]
    public IEnumerable<string> GetUserRoutes(DateTime effectiveDate)
    {
        ...
    }
}

// JavaScript Usage: effectiveDate="03/29/2019"
API.SendRequest("/api/UserRoutes", "GET", { effectiveDate: effectiveDate }, success, failure);

WebApiConfig

不确定是否相关,因为我只是为每个操作声明路线,但是...

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 }
        );
    }
}

API.SendRequest

这个函数只是 jQuery 的 $.ajax 函数的包装,没什么特别的。如果代码是必要的,我会提供它,但它适用于我的所有其他 API 调用,所以我无法想象它会是问题的根源。

这些操作几乎相同,为什么一个有效而另一个无效?

【问题讨论】:

  • 当您将日期字符串作为 URL 的一部分发送时,请使用 ISO8601 对其进行格式化。 https://localhost:44390/api/UserRoutes?effectiveDate=2019-03-29
  • 转到您发送的链接给了我一个有用的错误,显然我在另一个区域有一个名为 UserApiController 的控制器,路由无法处理。非常感谢,我猜路由在解决该操作时遇到了问题,因为它正在加载我的 Permissions 区域中的操作,但没有找到我请求的操作。

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


【解决方案1】:

按照 Igor 在 cmets 中所说的那样传递日期会显示一条错误消息,显示我在我的 Permissions 区域中有一个 Api 控制器,该控制器的路由也名为 api/UserRoutes

一旦我更改了路线的名称,问题就解决了。 我只是希望它从一开始就告诉我这个错误消息。

【讨论】:

    猜你喜欢
    • 2011-02-11
    • 1970-01-01
    • 2020-04-20
    • 1970-01-01
    • 2020-06-26
    • 1970-01-01
    • 2016-03-14
    • 2018-12-08
    • 1970-01-01
    相关资源
    最近更新 更多