- 跨域解决
1、使用Nuget添加Cors包
2、全局跨域
3、部分方法允许跨域
如果不想所有方法都能被跨域访问,可以使用[EnableCors]属性指定,具体实现如下:
a) WebApiConfig.cs文件保持开启跨域支持
b) 在方法或控制器上配置属性
- 跨域Session问题
1、Web Api默认关闭Session。开启方法如下:
在Global.asax文件中添加方法如下:
//初始化开启Session
public override void Init()
{
this.PostAuthenticateRequest += (sender, e) =>
{
HttpContext.Current.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Required);
};
base.Init();
}
2、由于跨域时默认是不允许操纵cookie的,这会导致每次跨域调用方法都是使用的不同的sessionId,开启session的意义就不存在了,需要进行如下设置进行解决:
a) WebApiConfig文件配置跨域的语句改为如下所示:
// 开启全局跨域
var cor = new EnableCorsAttribute("http://127.0.0.1:5500", "*", "*");
cor.SupportsCredentials = true;// 允许cookie发送,否则session不可用
config.EnableCors(cor);
b) 前端js配置全局ajax
// ajax全局设置
$.ajaxSetup({
xhrFields: {
withCredentials: true // 跨域允许存取cookie
}
});
- 参考文档
实现参考:https://www.cnblogs.com/landeanfen/p/5177176.html
方法跨域提示:https://yq.aliyun.com/wenzhang/show_56581
跨域session:https://www.cnblogs.com/zhaoshang/p/9378928.html
jquery ajax 设置全局(常量和变量):https://www.cnblogs.com/007sx/p/7048373.html
cors详解:https://blog.youkuaiyun.com/java_green_hand0909/article/details/78740765