gpt4 book ai didi

c# - 路由上的约束条目 'httpMethod' 必须具有字符串值

转载 作者:太空狗 更新时间:2023-10-29 20:54:44 27 4
gpt4 key购买 nike

我有一个 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") }
);

出于集成测试目的,我想向 HttpSelfHostServer 发出请求,以验证我们是否从 api 调用接收到正确的数据。我正在制作 HttpRequestMessage 如下:

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

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

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

同样的 url (http://localhost:XXXX/api/User/) 当我在浏览器中使用它时没有错误,所以我很确定问题必须在我通过 HttpClient 将请求发送到 HttpSelfHostServer 的方式。我曾尝试使用 HttpMethod.Get 常量来代替,但这也引发了同样的错误。

有人知道我该如何解决这个问题吗?

最佳答案

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

constraints: new { httpMethod = new System.Web.Http.Routing.HttpMethodConstraint(HttpMethod.Get) }

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

关于c# - 路由上的约束条目 'httpMethod' 必须具有字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18404226/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com