zoukankan      html  css  js  c++  java
  • 《Asp.Net Core3 + Vue3入坑教程》- 2.配置CORS策略解决跨域问题

    简介

    《Asp.Net Core3 + Vue3入坑教程》 此教程适合新手入门或者前后端分离尝试者。可以根据图文一步一步进操作编码也可以选择直接查看源码。每一篇文章都有对应的源码

    教程后期会将 .Net Core 3升级成 .Net Core 5

    目录

    《Asp.Net Core3 + Vue3入坑教程》系列教程目录

    Asp.Net Core后端项目

    1. 后端项目搭建与Swagger配置步骤
    2. (本文)配置CORS策略解决跨域问题
    3. AutoMapper & Restful API & DI
    4. EF Core & Postgresql
    5. (暂未发表敬请期待...).Net Core 3升级成 .Net Core 5
    6. (暂未发表敬请期待...)JWT

    Vue3 前端项目

    暂未发表敬请期待...

    本文简介

    本文为《Asp.Net Core3 + Vue3入坑教程》系列教程的第二篇 - 跨域问题处理。前后端分离遇到的最常见问题之一就是跨域问题。本文接着上文(后端项目搭建与Swagger配置步骤)继续为Asp .Net Core项目解决跨越问题

    Simple项目跨域问题处理步骤

    新建CRONTest.html用来验证跨域问题

    代码如下:

    注意: url: "https://localhost:44372/api/Values", 端口号要与Simple项目的一致

    
    <!DOCTYPE html><html>
    <head> 
    <meta charset="utf-8"> 
    <title> CRONTest </title>
    <script type="text/javascript" src="https://cdn.staticfile.org/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript" >
    $.ajax({
      type: "GET",
      url: "https://localhost:44372/api/Values", // 需要保证端口号与Simple项目的一致
      success: function(msg){
         alert( "CRONTest Success: " + msg );
       }
    });
    
    </script>
    </head>
    <body>
    <p>CRONTest</p>
    </body>
    </html>
    
    

    打开CRONTest.html,并按F12打开浏览器开发者工具,我们可以看到控制台报了跨域的错误

    为Simple项目增加跨域处理,在ServiceProvider文件夹下新建扩展类CORS.cs

    代码如下:

    注意:目前先允许所有请求,当能够明确前端域名的时候,再改掉WithOrigins方式!!!

    using Microsoft.Extensions.DependencyInjection;
    
    namespace Simple_Asp.Net_Core.ServiceProvider
    {
       public static class CORS
       {
           public static void AddCORS(this IServiceCollection services)
           {
                   services.AddCors(
                      options => options.AddPolicy(
                          "CorsTest",
                           // 目前先允许所有请求,当能够明确前端域名的时候,再改成WithOrigins方式
                           p => p.AllowAnyOrigin()
                                // 配置前端域名,注意端口号后不要带/斜杆
                                //p => p.WithOrigins("https://localhost:44372", "https://localhost:44372")
                                .AllowAnyHeader()
                                .AllowAnyMethod()
                                .WithExposedHeaders("Content-Disposition")));
           }
       }
    }
    

    配置Starup.cs

    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Http;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Hosting;
    using Simple_Asp.Net_Core.ServiceProvider;
    
    namespace Simple_Asp.Net_Core
    {
        public class Startup
        {
            // This method gets called by the runtime. Use this method to add services to the container.
            // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddCORS();
                services.AddMvc();
                services.AddSwagger();
            }
    
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                    app.UseSwagger();
                    app.UseSwaggerUI(c =>
                    {
                        c.SwaggerEndpoint("/swagger/v1/swagger.json", "ApiHelp V1");
                    });
                }
    
                app.UseCors("CorsTest");
    
                app.UseRouting();
                app.UseEndpoints(endpoints => endpoints.MapDefaultControllerRoute());
            }
        }
    }
    
    

    再次使用CRONTest.html调用后端接口

    这次能成功调用后端接口,解决了跨域问题

    CORS跨域问题处理完成!

    总结

    本文为Simple项目配置CORS策略来解决跨域问题,这时候前端项目可以正常请求后端服务。

    需要注意目前源码是允许所有请求,当能够明确前端域名的时候,要改掉WithOrigins方式!保证后端服务的安全!

    解决跨域问题有很多种,可以使用通过jsonp或者nginx代理等等

    GitHub源码

    注意:源码调试过程中如果出现xml文件路径错误,需要参照上文(后端项目搭建与Swagger配置步骤)Swagger配置“配置XML 文档文件”步骤,取消勾选然后再选中 ,将XML路径设置成与你的电脑路径匹配!

    https://github.com/Impartsoft/Simple_Asp.Net_Core/tree/master/Simple_Asp.Net_Core 2.CORS

    参考资料

    博客(推荐学习) https://www.cnblogs.com/laozhang-is-phi/p/9495618.html

    微软官方文档 https://docs.microsoft.com/zh-cn/aspnet/core/?view=aspnetcore-5.0

    CORS详解 http://www.ruanyifeng.com/blog/2016/04/cors.html

    CORS详解 https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

    欢迎大家批评指正,共同学习,共同进步!
    作者:Iannnnnnnnnnnnn
    出处:https://www.cnblogs.com/Iannnnnnnnnnnnn
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    node=day5
    封装异步API
    form表单的name作用
    关于app.use('/static', express.static(path.join(__dirname, 'public')))的理解
    node=day4
    PS切片
    WPF SDK研究 之 数据绑定
    C# WPF DataGrid控件实现三级联动
    wpf中的样式与模板
    WPF : ListBox的几种Template属性
  • 原文地址:https://www.cnblogs.com/Iannnnnnnnnnnnn/p/14438539.html
Copyright © 2011-2022 走看看