简体   繁体   English

Ajax发布到Web Api(不允许使用405方法)

[英]Ajax Post to Web Api (405 Method Not Allowed)

Having an issue when I am posting AngularJS data to Web API end point. 在将AngularJS数据发布到Web API端点时遇到问题。 From the client browser I receive: 从客户端浏览器,我收到:

405 (Method Not Allowed)
Response for preflight has invalid HTTP status code 405

I have two separate projects which both run in localhost. 我有两个单独的项目,都在localhost中运行。 On my Web Api I have set EnableCors() on config. 在我的Web Api上,我在配置上设置了EnableCors()

If I set content-type of the header to: 如果我将标题的内容类型设置为:

 'Content-type': 'application/x-www-form-urlencoded; charset=utf-8'

Then it's able to hit my Web API endpoint. 然后就可以访问我的Web API端点。 However my object argument is null. 但是我的对象参数为null。 Could this be XML format rather than JSON? 可以是XML格式而不是JSON吗? How do I go about resolving this? 我该如何解决这个问题?

Client side code: 客户端代码:

 function signUp(data) {
        $http({
            method: 'POST',
            url: 'http://localhost:15218/api/account/register',
            data: JSON.stringify(data),
            headers: {
                'Content-type': 'application/json'
            }

    }).then(function successCallback(response) {
            console.log(response);
        }, function errorCallback(response) {
            console.log(response);
        });
    }
}

Server Side Method signature: 服务器端方法签名:

    [HttpPost]
    [Route("Register")]
    public async Task<HttpResponseMessage> Register(UserCommand command)

You can enable cors on the service by adding global.asax file 您可以通过添加global.asax文件在服务上启用cors

protected void Application_BeginRequest(object sender, EventArgs e)
{
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
    if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
    {
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST, PUT, DELETE");

        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
        HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
        HttpContext.Current.Response.End();
    }
}

Response for preflight has invalid HTTP status code 405

Before making the POST request you want to make, the browser is making an OPTIONS request asking for permission. 在发出您要发出的POST请求之前,浏览器正在发出OPTIONS请求以寻求许可。

The server is responding to the OPTIONS request without a 200 response. 服务器正在响应OPTIONS请求,但没有200响应。 The error message tells you that explicitly. 错误消息会明确告诉您。 (Maybe Access-Control-Allow-Origin cause the problem) (可能是Access-Control-Allow-Origin引起了问题)

So before anything else, you must check for type of request method. 因此,在进行其他操作之前,您必须检查请求方法的类型。 If it is OPTIONS , pass 200 response code. 如果为OPTIONS ,则传递200响应代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM