【问题标题】:HTTPPost MVC 4 web apiHTTPPost MVC 4 网络 API
【发布时间】:2012-03-30 20:06:48
【问题描述】:

我正在构建一个 mvc 4 web api,但是当我尝试向 web api 发帖时,请求会返回

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

我的请求标头

User-Agent: Fiddler
Host: localhost:53393
Content-Length: 39
Content-Type: application/json

我的请求正文

{
  "username":"",
  "password":""
}

路线

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

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

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }

以及我控制器中的方法

[HttpPost]
public MethodResponse Authenticate(string username, string password)
{
    ConsoleServiceClient service = new ConsoleServiceClient();
    return service.Authenticate(username, password);
}

我使用的网址

http://localhost:53393/api/service/authenticate

我还是新手,但不知道为什么不支持 POST?

谢谢

【问题讨论】:

  • 你是如何发出post请求的?
  • 我在fiddler中构建并点击执行
  • 你的控制器叫ServiceController吗?
  • 是的,正常的 GET 请求工作正常

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


【解决方案1】:

尝试使用 http://localhost:53393/api/service 作为您的 URI,因为您的 API 路由中目前没有 {action} 段。

【讨论】:

  • 将 {action} 添加到 URI 模板并且它起作用了,也许更新答案以反映这一点
  • @Armand 无论哪种方式都有效。如果您要采用更多面向资源的方法,您可以将方法命名为 Post() 和控制器 Authenticate,然后您就不需要 {action} 并且可以删除“服务”路径段。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-24
  • 2021-12-26
  • 2016-06-23
  • 1970-01-01
  • 1970-01-01
  • 2014-11-01
相关资源
最近更新 更多