路径上的约束条目'httpMethod'必须具有字符串值

sco*_*192 6 c# asp.net httpserver asp.net-web-api asp.net-web-api-routing

我有一个asp.net Web API项目,在我的WebApiConfig文件中,我定义了以下路由:

config.Routes.MapHttpRoute(
    name: "Web API Get",
    routeTemplate: "api/{controller}",
    defaults: new { action = "Get" },
    constraints: new { httpMethod = new HttpMethodConstraint("GET") }
    );
Run Code Online (Sandbox Code Playgroud)

出于集成测试的目的,我想向a发出请求以HttpSelfHostServer验证我们是否从api调用中收回了正确的数据.我正在做HttpRequestMessage如下:

var httpMethod = new HttpMethod("GET");
var request = new HttpRequestMessage(httpMethod, "http://localhost:XXXX/api/User/");
var results = _client.SendAsync(request).Result;
Run Code Online (Sandbox Code Playgroud)

我希望这会调用UserController上的Get方法,然后返回该方法中定义的结果.但是,我得到以下异常:

System.InvalidOperationException:路由模板'api/{controller}'的路由上的约束条目'httpMethod'必须具有字符串值或者是实现'IHttpRouteConstraint'的类型

http://localhost:XXXX/api/User/当我在浏览器中使用它时,同样的url()可以正常工作,所以我很确定问题必须与我HttpSelfHostServer通过发送请求的方式相同HttpClient.我尝试过使用HttpMethod.Get常量,但这也引发了同样的错误.

有谁知道如何解决这个问题?

Dar*_*rov 16

确保您使用的proper type是约束:

constraints: new { httpMethod = new System.Web.Http.Routing.HttpMethodConstraint(HttpMethod.Get) }
Run Code Online (Sandbox Code Playgroud)

我猜你使用的System.Web.Routing.HttpMethodConstraint是一个完全不同的用于ASP.NET MVC路由的类,它与ASP.NET Web API路由无关.

  • 是的,当他们为MVC中提供但在不同程序集和命名空间下可用的Web API的每一个类都进行了欺骗时,微软创造了一个混乱.这是错误的常见原因. (4认同)