asp net core mvc 跨域ajax解决方案
2024-08-31 06:59:10
1、配置服务端
在Startup文件中国配置Cors策略:
IEnumerable<Client> clients= Configuration.GetSection("Clients").Get(typeof(IEnumerable<Client>)) as IEnumerable<Client>; List<string> urls = new List<string>();
foreach (var client in clients)
{
urls.AddRange(client.AllowedCorsOrigins);
}
services.AddCors(options =>
{
options.AddPolicy("default",
builder => builder.WithOrigins(urls.ToArray())
.AllowAnyHeader()
.AllowCredentials()
.AllowAnyMethod());
});
启用CORS策略,可以在Startup文件中配置,也可以在具体的ApiController中配置,代码分别如下:
app.UseCors("default");
[Authorize]
[EnableCors("default")]
public class NavigationMenuController:Controller
{
private NavigationMenuService navigationMenuService; public NavigationMenuController(NavigationMenuService navigationMenuService)
{
this.navigationMenuService = navigationMenuService;
}
}
2、JQuery请求
$.ajax({
url: 'http://localhost:5000/api/Private/Values/Identity',
type: 'GET',
dataType: 'json',
crossDomain: true,
xhrFields: {
withCredentials: true
},
success: function (result) {
$('#platformResult').val(JSON.stringify(result));
}
});
红字是关键 ,值得注意的是需要配置 withCredentials,否则请求不会带上Cookie。
3、 axios请求
axios({
url:
config.authority +
"/api/xxxxxxxxxx?clientId=" +
escape(config.client_id),
method: "GET",
withCredentials: true
}).then(function (result) {
if (result.success == undefined) {
self.menuItems = result || [];
}
});
’
最新文章
- OGNL的使用
- adminLTE的自动化菜单
- sql操作
- 简单模仿javascript confirm方法的例子
- 移动平台WEB前端开发技巧汇总
- 配置Linux系统网卡连接网络
- Winform学习手册(目录)
- socket实现局域网通信
- javascript 正则介绍
- [转]POJ1006: 中国剩余定理的完美演绎
- WordCount结对项目
- tomcat启动报错 关键字:java.lang.NoClassDefFoundError和 java.lang.ClassNotFoundExceeption
- laravel 接口跨域
- Python3函数式编程
- cxf 相关问题
- Centos 7 配置 VNCServer 經驗
- 每日笔记---使用@ConfigurationProperties读取yml配置
- RelativeLayout相对布局中属性值
- 【shiro】2.spring整合shiro,注解控制shiro用户/角色/权限And/OR,没有权限跳转到固定页面
- Android 开发 -------- 自己定义View 画 五子棋