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微服务(三)——【跨域配置】

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

红目香薰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值