ASP.NET Core微服务(三)——【跨域配置】
生活随笔
收集整理的這篇文章主要介紹了
ASP.NET Core微服务(三)——【跨域配置】
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
ASP.NET Core微服務(三)——【跨域配置】
對應練習demo(跨域)下載路徑(1積分):【https://download.csdn.net/download/feng8403000/15136711】
對應練習sql下載路徑(0積分):【https://download.csdn1/.net/download/feng8403000/15134699】
未跨域的錯誤提示:【No 'Access-Control-Allow-Origin' header is present on the requested resource.?】
解決的方法如下:
跨域的【Startup.cs】文件配置
1、聲明跨域策略名稱
//聲明跨域策略名稱readonly string MyCorsPolicy = "CorsPolicy";添加位置:
2、引入跨域服務
//引入跨域服務services.AddCors(options => options.AddPolicy(MyCorsPolicy, builder =>{builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();services.AddControllers();}));添加位置:
3、允許跨域請求
//允許跨域請求app.UseCors();app.UseEndpoints(endpoints =>{endpoints.MapControllers().RequireCors(MyCorsPolicy) ;});添加位置:?
4、跨域測試(采用JQuery的ajax直接測試):
<!DOCTYPE html> <html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>跨域測試</title><script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js" /> </head><body><script>$(function() {$.ajax({url: "http://localhost:5000/api/Test/GetInfo",dataType: "json",type: "get",success: function(data) {data.forEach(element => {document.write(element.id);document.write(element.createDate);document.write(element.nickName);document.write(element.introduce);document.write("<br/>");});}});});</script> </body></html>效果如下:
成功跨域。
5、總結:
a)、跨域的三個配置分別的位置不同,請確定編寫位置,本文有圖片提示。
b)、本文直接做的【get】測試,如需【post】測試,請將【ajax的type值改為post】
希望此文對大家有所幫助,后續會編寫
ASP.NET Core微服務(四)——【靜態vue使用axios解析接口】、
ASP.NET Core微服務(五)——【vue腳手架解析接口】、
ASP.NET Core微服務(六)——【redis操作】、
ASP.NETCore微服務(七)——【docker部署linux上線】
等文章。
此文標題為ASP.NET Core微服務(二)——ASP.NET Core微服務(三)——【跨域配置】
總結
以上是生活随笔為你收集整理的ASP.NET Core微服务(三)——【跨域配置】的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ASP.NET Core微服务(二)——
- 下一篇: ASP.NET Core微服务(四)——