zl程序教程

您现在的位置是:首页 >  后端

当前栏目

ASP.NET Core微服务(三)——【跨域配置】

2023-09-14 09:04:59 时间

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