《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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM