0

我正在尝试从 web api(在 MVC4 项目中创建)调用 POST 方法,但无法访问它。

我的 web api 配置如下,

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

我正在尝试调用以下方法,

    [HttpPost]
    public bool Delete(Int64 Id)
    {           
        return true;
    }

所有的 GET 方法都被调用。

当我尝试访问它时,浏览器正在显示,

“不允许使用 http 405 方法”

当看到它显示的响应时,

{"Message":"请求的资源不支持 http 方法 'GET'。"}

请帮帮我。

4

1 回答 1

4

当我尝试访问它时,浏览器正在显示

嗯,这很正常。浏览器发送 GET 请求。您的方法只能通过 POST 请求调用。

下面是一个示例 HTTP 请求的样子:

POST /someresource/delete/123 HTTP/1.1
Host: www.example.com
Content-Type: application/json
Content-Length: 0
Connection: close

您可以在 Fiddler 中尝试该请求或编写一个示例 HTTP 客户端来发送 POST 请求。

啊,顺便说一句,为什么不坚持标准的 RESTful 约定:

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

和你的行动:

public bool Delete(Int64 Id)
{           
    return true;
}

并调用它:

DELETE /someresource/123 HTTP/1.1
Host: www.example.com
Content-Type: application/json
Content-Length: 0
Connection: close

Notice that the standard RESTful convention dictates that the action name should not be used in your routes. It is the HTTP verb that decides which action to be invoked. So your actions should be named accordingly to the HTTP verb. In your example you want to delete some resource with a specified id, so your controller action should be named Delete (as it is currently) and it should be accessible through the DELETE HTTP verb.

于 2013-10-23T13:29:49.933 回答