预检的响应具有无效的HTTP状态代码405.不允许使用方法。 Cross Origin请求正在发生这种情况

时间:2018-03-11 11:17:12

标签: asp.net-mvc angular cors

我有一个Angular 2应用程序作为前端,我在C#中命中我的后端API以获取POST请求。由于请求是跨源的,浏览器将我的POST方法转换为OPTIONS方法。

为了解决这个问题,我将config.EnableCors();放在我的后端API中的webapiconfig.cs文件中,但它没有帮助。
另外,尝试在web.config中添加它: -

add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" 

根本不工作。
在浏览器标题中显示 - >

Request URL:http://localhost:4883/api/employeeapi
Request Method:OPTIONS
Status Code:405 Method Not Allowed
Remote Address:[::1]:4883
Referrer Policy:no-referrer-when-downgrade

如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

通过在Global.asax

中添加以下代码来获得解决方案
protected void Application_BeginRequest(object sender, EventArgs e)
{

  HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");

            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                //These headers are handling the "pre-flight" OPTIONS call sent by the browser
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, 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();
            }
}