c# - WebAPI 路由 : Combining Attributes and HttpConfiguration settings

标签 c# .net asp.net-web-api

我正在尝试为同一条路线使用 GETPOST:

我已经注册了以下内容:

  config.MapHttpAttributeRoutes();

  config.Routes.MapHttpRoute(
                name: "MyGetMethod",
                routeTemplate: "api/v1/users/{user}",
                defaults: new
                              {
                                  controller = "Users",
                                  action = "MyGetMethod"
                              },
                constraints: null,
                handler: HttpClientFactory.CreatePipeline(
                    new HttpControllerDispatcher(config),
                    routeHandlerFactory.Create()));

  config.Routes.MapHttpRoute(
                name: "MySetMethod",
                routeTemplate: "api/v1/users/{user}",
                defaults: new
                              {
                                  controller = "Users",
                                  action = "MySetMethod"
                              },
                constraints: null,
                handler: HttpClientFactory.CreatePipeline(
                    new HttpControllerDispatcher(config),
                    routeHandlerFactory.Create()));

我的 UsersController.cs 包含:

 [HttpPost]
    public HttpResponseMessage MySetMethod(string user)
    {
        return new HttpResponseMessage(HttpStatusCode.NotImplemented);
    }


 [HttpGet]
    public HttpResponseMessage MyGetMethod(string user)
    {
        return new HttpResponseMessage(HttpStatusCode.NotImplemented);
    }

这行不通。 GET 工作正常,但是当我使用 POST 时,WebAPI 仍然重定向到 GET 方法,我得到错误:

"Message": "The requested resource does not support http method 'POST'."

如果我注释掉 GET 方法的注册,那么 POST 就可以正常工作。

是不是因为我在 Controller 方法上使用属性 [HttpPost][HttpGet] 的组合,而不是将它们标记为 constraints?

我怎样才能在同一条路线上有 GETPOST

最佳答案

如果你用这个就可以了

config.MapHttpAttributeRoutes();

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

关于c# - WebAPI 路由 : Combining Attributes and HttpConfiguration settings,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38698528/

相关文章:

c# - 如何在 C# 中使用 Selenium 定位表格中的文本并引用元素单击另一个元素?

c++ - 在 Visual C++ 中执行此操作的更好方法是什么?

c# - 在内存中创建 FileStream 而不是在磁盘上保存一个物理文件

asp.net-mvc - 为 MVC 和 Web Api Controller 采用 Action 过滤器

c# - 重载 +=、+、== 和 != 运算符

c# - 网络服务中的其他方法未显示

c# - 从不同命名空间中的枚举复制值

c# - 比较c#中的日期并考虑空值

c# - 在 Entity Framework Core 中使用动态过滤器

asp.net - Web Api - 如何检测何时完成发送响应