.NET Core 3 Web Api Cors fetch 一直 307 Temporary Redirect

来源:https://www.cnblogs.com/VAllen/archive/2020/02/26/dotnet-core-3-cors-fetch-response-307-temporary-redirect.html
-Advertisement-
Play Games

.NET Core 3 Web Api Cors fetch 一直 307 Temporary Redirect 繼上一篇 ".net core 3 web api jwt 一直 401" 為添加 所述的坑後, 本次為添加 ,又踩坑了。 自從 .NET Core 2.2 之後,CORS跨域配置代碼發 ...


.NET Core 3 Web Api Cors fetch 一直 307 Temporary Redirect

繼上一篇 .net core 3 web api jwt 一直 401 為添加JWT-BearerToken認證所述的坑後,
本次為添加CORS跨域,又踩坑了。

自從 .NET Core 2.2 之後,CORS跨域配置代碼發生了很大變化。
在 .NET Core 3.1 中,本作者碰到各種HTTP錯誤,諸如 500、307、401 等錯誤代碼...
在必應Bing和不斷Debug調整配置代碼位置後,得知:

  1. AllowAnyOrigin 方法,在新的 CORS 中間件已經被阻止使用允許任意 Origin,所以該方法無效。
  2. AllowCredentials 方法,自從 .NET Core 2.2 之後,不允許和AllowAnyOrigin同時調用。
  3. WithOrigins 方法,在 .NET Core 3.1 中有bug,具體原因未知,暫時只能用SetIsOriginAllowed(t=> true)代替,等效.AllowAnyOrigin方法。
  4. 創建項目預設的模板中,app.UseHttpsRedirection()在前面,所以我將app.UseCors()放在它後面,這是導致HTTP 307 Temporary Redirect福報的根本原因之一。
  5. 度娘告訴我,app.UseCors()方法要在app.UseAuthentication()之後,是誤人子弟的,其實放在它前面也可以,並且app.UseCors()要在app.UseRouting()之後,app.UseEndpoints()app.UseHttpsRedirection()之前
  6. 使用fetch跨域請求時,要註意controller的action是否有設置除了HttpOptions之外的其它Http Method方法,如果有要加上HttpOptions標記特性,因為fetch跨域請求會先執行OPTIONS預請求。
  7. 使用fetch請求需要JWT認證的介面時,除了在HTTP Headers設置Authorization之外,還需要設置'credentials': 'include'
  8. app.UseXxxxxx方法,引入中間件時,要註意管道(Middleware)註冊順序。

參考:

源代碼

以下是在 .NET Core 3.1下經過嚴謹測試,可以JWT認證CORS跨域IIS托管自寄主運行的源代碼,僅供參考。

WebApi.csproj

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <RootNamespace>WebApi</RootNamespace>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.1.2" />
    <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="3.1.2" />
    <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="3.1.2" />
    <PackageReference Include="Microsoft.Extensions.Logging.EventSource" Version="3.1.2" />
    <PackageReference Include="Microsoft.Extensions.Logging.TraceSource" Version="3.1.2" />
    <PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="3.1.2" />
    <PackageReference Include="Microsoft.TeamFoundationServer.Client" Version="16.153.0" />
    <PackageReference Include="Microsoft.VisualStudio.Services.Client" Version="16.153.0" />
    <PackageReference Include="Microsoft.VisualStudio.Services.InteractiveClient" Version="16.153.0" />
    <PackageReference Include="NLog.Web.AspNetCore" Version="4.9.0" />
  </ItemGroup>
</Project>

Program.cs

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using System.Diagnostics;
using System.IO;

namespace WebApi
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args)
        {
            return Host.CreateDefaultBuilder(args)
                .ConfigureLogging((context, logging) =>
                {
                    logging.ClearProviders()
#if DEBUG
                        .AddConsole()
                        .AddDebug()
                        .AddEventLog()
                        .AddTraceSource(new SourceSwitch(nameof(Program), "Warning"), new ConsoleTraceListener())
#endif
                        .AddNLog();
                })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseContentRoot(Directory.GetCurrentDirectory())
                       .UseKestrel()
                       .UseIISIntegration()
                       .UseIIS()
                       .UseStartup<Startup>();
                });
        }
    }
}

Startup.cs

using MCS.Vsts.Options;
using MCS.Vsts.Services;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
using System.Text;

namespace WebApi
{
    public class Startup
    {
        public IConfiguration Configuration { get; }

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            //認證
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    var secretBytes = Encoding.UTF8.GetBytes(Configuration["ServerConfig:Secret"]);
                    options.TokenValidationParameters = new TokenValidationParameters()
                    {
                        IssuerSigningKey = new SymmetricSecurityKey(secretBytes),
                        ValidateIssuer = false,
                        ValidateAudience = false,
                        ValidateActor = false,
                        RequireSignedTokens = true,
                        RequireExpirationTime = true,
                        ValidateLifetime = true
                    };
                });

            //跨域
            services.AddCors(options =>
            {
                options.AddDefaultPolicy(builder =>
                {
                    builder
                    //允許任何來源的主機訪問
                    //TODO: 新的 CORS 中間件已經阻止允許任意 Origin,即設置 AllowAnyOrigin 也不會生效
                    //AllowAnyOrigin()
                    //設置允許訪問的域
                    //TODO: 目前.NET Core 3.1 有 bug, 暫時通過 SetIsOriginAllowed 解決
                    //.WithOrigins(Configuration["CorsConfig:Origin"])
                    .SetIsOriginAllowed(t=> true)
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials();
                });
            });

            //TODO: do something...
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                //Enabled HSTS
                app.UseHsts();
            }

            //TODO: 要放在UseCors之後
            //app.UseHttpsRedirection();

            app.UseRouting();

            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
            });

            //TODO: UseCors要在UseRouting之後,UseEndpoints 和 UseHttpsRedirection 之前
            app.UseCors();

            app.UseAuthentication();

            app.UseAuthorization();

            app.UseHttpsRedirection();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "https_port": 44370,
  "urls": "http://*:50867",
  "ServerConfig": {
    "Secret": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
  },
  "CorsConfig": {
    "BaseUri": "http://myserver"
  }
}

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 訪問許可權控制一個類的public的成員變數、成員函數,可以通過類的實例變數進行訪問。一個類的protected的成員變數、成員函數,無法通過類的實例變數進行訪問,但是可以通過類的友元函數、友元類進行訪問。一個類的private的成員變數、成員函數,無法通過類的實例變數進行訪問,但是可以通過類的友元函... ...
  • django項目中遇到要實現定時任務,所以選用了簡單易用的django-crontab插件。 1、安裝 django-crontab pip install django-crontab 2、定時要執行的腳本 先寫個簡單的測試腳本。crontab/crons.py import datetime d ...
  • 開發環境: Windows操作系統開發工具: MyEclipse+Jdk+Tomcat+Mysql資料庫運行效果圖 源碼及原文鏈接:https://javadao.xyz/forum.php?mod=viewthread&tid=50 ...
  • 最近django項目中使用到了定製後臺定時任務時報出“”及“ in crontab file, can't install”。經確認,根本原因是crontab文件中時間定義不正確導致的。簡單記錄一下這個,同時確認一下crontab中時間格式的規範,供參考。 1.具體報錯信息如下 ora10g@sec ...
  • 開發環境: Windows操作系統開發工具: Eclipse+Jdk+Tomcat+MySQL運行效果圖 源碼及原文鏈接:https://javadao.xyz/forum.php?mod=viewthread&tid=54 ...
  • 用scrapy只創建一個項目,創建多個spider,每個spider指定items,pipelines.啟動爬蟲時只寫一個啟動腳本就可以全部同時啟動。 本文代碼已上傳至github,鏈接在文未。 一,創建多個spider的scrapy項目 scrapy startproject mymultispi ...
  • WPF dotnet core 3.1 基於 `Microsoft.Extensions.Localization` 實現基本的多語言支持 ...
  • 在前一章已經學習過WPF動畫的第一條規則——每個動畫依賴於一個依賴項屬性。然而,還有另一個限制。為了實現屬性的動態化(換句話說,使用基於時間的方式改變屬性的值),需要有支持相應數據類型的動畫類。例如,Button.Width屬性使用雙精度數據類型。為實現屬性的動態化,需要使用DoubleAnimat ...
一周排行
    -Advertisement-
    Play Games
  • C#TMS系統代碼-基礎頁面BaseCity學習 本人純新手,剛進公司跟領導報道,我說我是java全棧,他問我會不會C#,我說大學學過,他說這個TMS系統就給你來管了。外包已經把代碼給我了,這幾天先把增刪改查的代碼背一下,說不定後面就要趕鴨子上架了 Service頁面 //using => impo ...
  • 委托與事件 委托 委托的定義 委托是C#中的一種類型,用於存儲對方法的引用。它允許將方法作為參數傳遞給其他方法,實現回調、事件處理和動態調用等功能。通俗來講,就是委托包含方法的記憶體地址,方法匹配與委托相同的簽名,因此通過使用正確的參數類型來調用方法。 委托的特性 引用方法:委托允許存儲對方法的引用, ...
  • 前言 這幾天閑來沒事看看ABP vNext的文檔和源碼,關於關於依賴註入(屬性註入)這塊兒產生了興趣。 我們都知道。Volo.ABP 依賴註入容器使用了第三方組件Autofac實現的。有三種註入方式,構造函數註入和方法註入和屬性註入。 ABP的屬性註入原則參考如下: 這時候我就開始疑惑了,因為我知道 ...
  • C#TMS系統代碼-業務頁面ShippingNotice學習 學一個業務頁面,ok,領導開完會就被裁掉了,很突然啊,他收拾東西的時候我還以為他要旅游提前請假了,還在尋思為什麼回家連自己買的幾箱飲料都要叫跑腿帶走,怕被偷嗎?還好我在他開會之前拿了兩瓶芬達 感覺感覺前面的BaseCity差不太多,這邊的 ...
  • 概述:在C#中,通過`Expression`類、`AndAlso`和`OrElse`方法可組合兩個`Expression<Func<T, bool>>`,實現多條件動態查詢。通過創建表達式樹,可輕鬆構建複雜的查詢條件。 在C#中,可以使用AndAlso和OrElse方法組合兩個Expression< ...
  • 閑來無聊在我的Biwen.QuickApi中實現一下極簡的事件匯流排,其實代碼還是蠻簡單的,對於初學者可能有些幫助 就貼出來,有什麼不足的地方也歡迎板磚交流~ 首先定義一個事件約定的空介面 public interface IEvent{} 然後定義事件訂閱者介面 public interface I ...
  • 1. 案例 成某三甲醫預約系統, 該項目在2024年初進行上線測試,在正常運行了兩天後,業務系統報錯:The connection pool has been exhausted, either raise MaxPoolSize (currently 800) or Timeout (curren ...
  • 背景 我們有些工具在 Web 版中已經有了很好的實踐,而在 WPF 中重新開發也是一種費時費力的操作,那麼直接集成則是最省事省力的方法了。 思路解釋 為什麼要使用 WPF?莫問為什麼,老 C# 開發的堅持,另外因為 Windows 上已經裝了 Webview2/edge 整體打包比 electron ...
  • EDP是一套集組織架構,許可權框架【功能許可權,操作許可權,數據訪問許可權,WebApi許可權】,自動化日誌,動態Interface,WebApi管理等基礎功能於一體的,基於.net的企業應用開發框架。通過友好的編碼方式實現數據行、列許可權的管控。 ...
  • .Net8.0 Blazor Hybird 桌面端 (WPF/Winform) 實測可以完整運行在 win7sp1/win10/win11. 如果用其他工具打包,還可以運行在mac/linux下, 傳送門BlazorHybrid 發佈為無依賴包方式 安裝 WebView2Runtime 1.57 M ...