选项 405(不允许的方法)web api 2 [英] OPTIONS 405 (Method Not Allowed) web api 2

查看:32
本文介绍了选项 405(不允许的方法)web api 2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个 web api 2 并且我正在尝试对其进行跨域请求,但是我收到以下错误:

I have created a web api 2 and I'm trying to do a cross domain request to it but I'm getting the following error:

OPTIONS http://www.example.com/api/save 405(不允许的方法)

OPTIONS http://www.example.com/api/save 405 (Method Not Allowed)

我环顾四周,大多数解决此问题的方法都是说我需要从 NuGet 安装 COR 并启用它,因此我已经安装了该软件包并用

I have had a look around and most resolutions for this problem are saying that I need to install CORs from NuGet and enable it so I have installed the package and marked my controller with

[EnableCors("*", "*", "*")]

但这仍然没有解决问题.

But this still hasn't resolved the problem.

我的ApiController中只有以下Save方法:

[ResponseType(typeof(int))]
public IHttpActionResult Save(Student student)
{
    if (ModelState.IsValid)
    {
        using (StudentHelper helper = new StudentHelper())
        {
            return Ok(helper.SaveStudent(student));
        }
    }
    else
    {
        return BadRequest(ModelState);
    }
}

这是我来自不同域的 js:

This is my js from a different domain:

$.ajax({
    type: "POST",
    crossDomain: true,
    data: JSON.stringify(student),
    crossDomain: true,
    url: 'http://www.example.com/api/save',
    contentType: "application/json",
    success: function (result) {
        console.log(result);
    }
});

我还需要做些什么来启用此功能吗?

Is there something else I need to do to enable this?

推荐答案

最后我通过改变ajax请求解决了这个问题.我发现 OPTIONS 预检仅在某些情况下发送 - 其中之一是如果请求包含不是以下类型之一的 Content-Type:

In the end I have solved this by changing the ajax request. I found out that the OPTIONS preflight is only sent in certain situations - one of them being if the request contains a Content-Type that is not one of the following types:

  • application/x-www-form-urlencoded
  • multipart/form-data
  • 文本/纯文本

因此,通过删除我的 ajax 请求中的内容类型并将其更改为以下内容:

So by removing the content-type in my ajax request and changing it to the following:

$.ajax({
    type: "POST",
    crossDomain: true,
    data: student,
    dataType: 'json',
    url: 'http://www.example.com/api/save',
    success: function (result) {
        console.log(result);
    }
});

我能够让它工作.

此页面包含有关简单请求和如何避免预检请求

这篇关于选项 405(不允许的方法)web api 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆