【问题标题】:nohttp resource was found that matches the request uri没有找到与请求 uri 匹配的 http 资源
【发布时间】:2017-09-28 18:18:39
【问题描述】:

我正在尝试开发一个允许在同一地址获取和发布请求的 api。

public class DataController : ApiController
{

   [HttpGet]
   public DataResponse Foo()
   {
     return GetNext();
   }

   [HttpPost]
   public void Foo(long p1, string p2)
   {
     SaveValue(p1,p2);
   }
}

GET 工作正常。调用POST方法时,出现如下错误:

请求的资源不支持 http 方法 'POST'

我的 WebApiConfig 如下所示:

public static class WebApiConfig
  {
    public static void Register(HttpConfiguration config)
    {
      config.EnableCors();
      config.MapHttpAttributeRoutes();
      config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
      config.Routes.MapHttpRoute(name: "DefaultApi", routeTemplate: "api/{controller}/{action}");
    }
  }

知道我需要更改什么才能使其正常工作吗?

【问题讨论】:

    标签: asp.net-web-api


    【解决方案1】:

    您可以通过两种方式做到这一点-

    1- 更改调用 API 的方式,即 - 在 url 中传递值,例如 <url>?p1=value&p2=value

    2- 将 Web API 中的 Action 的签名更改为

    public void Foo([FromBody] MyContract data)
    

    其中MyContract 是一个具有两个属性的类

    public class MyContract
    {
        public long p1 { get; set; }
        public string p2 { get; set; }
    }
    

    这是因为默认情况下,参数绑定是通过 URL 完成的,而您通过正文传递它们。

    【讨论】:

    • 非常感谢,Ipsit。像魅力一样工作:-)
    猜你喜欢
    • 2021-09-06
    • 2016-12-01
    • 2017-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-02
    • 1970-01-01
    相关资源
    最近更新 更多