ASP.NET Core微服务(三)——【跨域配置】
生活随笔
收集整理的這篇文章主要介紹了
ASP.NET Core微服务(三)——【跨域配置】
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
ASP.NET Core微服務(wù)(三)——【跨域配置】
對(duì)應(yīng)練習(xí)demo(跨域)下載路徑(1積分):【https://download.csdn.net/download/feng8403000/15136711】
對(duì)應(yīng)練習(xí)sql下載路徑(0積分):【https://download.csdn1/.net/download/feng8403000/15134699】
未跨域的錯(cuò)誤提示:【No 'Access-Control-Allow-Origin' header is present on the requested resource.?】
解決的方法如下:
跨域的【Startup.cs】文件配置
1、聲明跨域策略名稱(chēng)
//聲明跨域策略名稱(chēng)readonly string MyCorsPolicy = "CorsPolicy";添加位置:
2、引入跨域服務(wù)
//引入跨域服務(wù)services.AddCors(options => options.AddPolicy(MyCorsPolicy, builder =>{builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();services.AddControllers();}));添加位置:
3、允許跨域請(qǐng)求
//允許跨域請(qǐng)求app.UseCors();app.UseEndpoints(endpoints =>{endpoints.MapControllers().RequireCors(MyCorsPolicy) ;});添加位置:?
4、跨域測(cè)試(采用JQuery的ajax直接測(cè)試):
<!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>跨域測(cè)試</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、總結(jié):
a)、跨域的三個(gè)配置分別的位置不同,請(qǐng)確定編寫(xiě)位置,本文有圖片提示。
b)、本文直接做的【get】測(cè)試,如需【post】測(cè)試,請(qǐng)將【ajax的type值改為post】
希望此文對(duì)大家有所幫助,后續(xù)會(huì)編寫(xiě)
ASP.NET Core微服務(wù)(四)——【靜態(tài)vue使用axios解析接口】、
ASP.NET Core微服務(wù)(五)——【vue腳手架解析接口】、
ASP.NET Core微服務(wù)(六)——【redis操作】、
ASP.NETCore微服務(wù)(七)——【docker部署linux上線(xiàn)】
等文章。
此文標(biāo)題為ASP.NET Core微服務(wù)(二)——ASP.NET Core微服務(wù)(三)——【跨域配置】
總結(jié)
以上是生活随笔為你收集整理的ASP.NET Core微服务(三)——【跨域配置】的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: ASP.NET Core微服务(二)——
- 下一篇: ASP.NET Core微服务(四)——