一、问题描述
1.1、错误信息
VUE 前端调用C# - ASP.NET API 是报如下错误
xhr.js:178 OPTIONS http://localhost:44383/api/Login/login 405 (Method Not Allowed)
Access to XMLHttpRequest at 'http://localhost:44383/api/Login/login' from origin 'http://localhost:9529' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
1.2、VUE 前端调用代码
export function login(data) {
return request({
url: '/api/v1/Login/Login',
method: 'post',
data
})
}
1.2、后端 ASP.NET WEB API
public class V1LoginController : ApiController
{
/// <summary>
///
/// </summary>
/// <remarks>
/// 请求示例
///
/// Post api/Login/Login
///
/// {
/// "username":"admin",
/// "password":"c8837b23ff8aaa8a2dde915473ce0991",
/// }
/// </remarks>
/// <param name="jsonText"></param>
/// <returns></returns>
[SwaggerResponse(HttpStatusCode.OK, Description = "正常返回", Type = typeof(RSS_SSDDS.Model.Account.PostLogin.Response))]
[SwaggerResponse(HttpStatusCode.BadRequest, Description = "错误返回", Type = typeof(RSS_SSDDS.Model.Account.PostLogin.Response))]
[HttpPost]
[Route("api/v1/Login/Login")]
public async Task<IHttpActionResult> Login([FromBody]dynamic jsonText)
{
RSS_SSDDS.Model.Account.PostLogin.Response res = new RSS_SSDDS.Model.Account.PostLogin.Response();
try
{
HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];
String clientIP = context.Request.UserHostAddress;
var uid = jsonText.username;
var pw = jsonText.password;
return Ok(res);
}
catch (Exception e)
{
log.Error("Login异常:" + e.Message);
res.Exception(e);
return Ok(res);
}
}
}
二、解决方案:修改 ASP.NET Web API 得跨域配置
../App_Start/WebApiConfig.cs 启动注册
SupportsCredentials[Access-Control-Allow-Credentials] 设置为true, 支持用户凭据。
EnableCorsAttribute的第一个参数origins[Access-Control-Allow-Origin] 设置为 * ,允许所有域名都可访问。
using System.Web.Http.Cors;
public static void Register(HttpConfiguration config)
{
// Web API 配置和服务
// var allowOrigins = ConfigurationManager.AppSettings["cors_allowOrigins"];
var globalCors = new EnableCorsAttribute("*", "*", "*")
{
SupportsCredentials = true
};
config.EnableCors(globalCors);
}
注、使用IIS搭建的网站
注意调整合适的托管模式:集成与经典加载的配置有很大的不同,设置不合理也会出现跨域报错