ASP.NET WEBAPI 跨域请求 405错误


浏览器报错

本来没有报这个错,当我在ajax中添加了请求头信息时报错

405的报错大概就是后端程序没有允许此次请求,要解决这个问题,就是在后端程序中允许请求通过。具体操作就是修改web.config配置项,如下图所示:

修改后就是这个样子:

添加的配置信息如下:





"Access-Control-Allow-Origin" />
"Access-Control-Allow-Headers" />
"Access-Control-Allow-Methods" />

"Access-Control-Allow-Origin" value="*" />
"Access-Control-Allow-Headers" value="*" />
"Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE" />

------------------------------------------------

/// 
/// 允许预请求跨域
/// 
/// 
/// 
protected void Application_BeginRequest(object sender, EventArgs e)
{
    var res = HttpContext.Current.Response;
    var req = HttpContext.Current.Request;
    res.AppendHeader("Access-Control-Allow-Headers", "Content-Type, X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Date, X-Api-Version, X-File-Name,Token,Cookie");
    res.AppendHeader("Access-Control-Allow-Methods", "POST,GET,PUT,PATCH,DELETE,OPTIONS");
    res.AppendHeader("Access-Control-Allow-Origin","*");
}

其中Access-Control-Allow-Headers配置项的value值需要根据实际情况进行配置,如果需要在请求头中添加参数,那就要在这里把参数名称加进去。
————————————————
原文链接:https://blog.csdn.net/liangmengbk/article/details/109212148