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

标签 c# asp.net asp.net-web-api httpserver 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") }
    );

出于集成测试目的,我想向 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/

相关文章:

c# - 系统.Data.SqlClient.SqlException : login failed for user '......'

c# - 尝试写入 C# 的现有 XML 文件

c# - 隐式委托(delegate)转换

c# - Unity播放动画后如何启动代码?

asp.net - 防止登录用户访问asp.net mvc 5中的登录页面

c# - 无法覆盖 Azure Web App 中的服务器证书验证

c# - 从 Angular JS 调用 Web API 错误 : The 'Access-Control-Allow-Origin' header contains multiple values, Origin is not allowed access

c# - 我们如何隐藏 WebAPI 中的属性?

asp.net-web-api - IdentityServer3和Web API在同一进程中

c# - CustomWebViewRenderer DownloadManager 与 CopyBackForwardList 的问题