使用两个路由参数调用时出现 HTTP 400

HTTP 400 When Calling With Two Route Params

为什么这个 HTTP 请求返回 400?

[RoutePrefix("common/api/trusts/{trustID}/periods")]
public class PeriodsController : ApiController
{
    [Route("{trustPeriodID}/getPeriodStartEndDates")]
    public object GetPeriodStartEndDates(short trustID, short trustPeriodID)
    {
        return null;
    }
}

调用如下:

$http.get("https://localhost:44300/common/api/trusts/1/periods/111811/getPeriodStartEndDates")
.then(function (result) {
     //do something with the result                       
});

我正在使用 Microsoft.AspNet.WebApi.Core.5.2.3 和 Angularjs.

首先,short的范围是-32,768到32,767,你的trustPeriodID - 111811远远超出范围。您可以将其类型设置为 int

public object GetPeriodStartEndDates(short trustID, int trustPeriodID)

此外,请确保您已根据此 link:

配置 CORS

https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api#enable-cors

要全局启用 CORS,请在 WebApiConfig.cs 中添加以下代码:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {

        config.MapHttpAttributeRoutes();

        //replace the url with your own Angular origin
        var cors = new EnableCorsAttribute("http://localhost:4200", "*", "*");
        config.EnableCors(cors);

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