簡體   English   中英

在 .NET 核心 6 中啟用 Cors

[英]enable Cors in .NET Core 6

我最近使用 .NET Core 6,我想使用 web API 從 ZA565B176ECE81D651B5C08C3 上傳文件但總是得到

“請求的資源上不存在‘Access-Control-Allow-Origin’ header”

錯誤。 Startup.cs 代碼:

  public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<Views.App.ConnectionStrings>(configuration.GetSection(nameof(Views.App.ConnectionStrings)));
        services.AddControllersWithViews().AddNewtonsoftJson();
        services.AddControllersWithViews(options =>
        {
            options.InputFormatters.Insert(0, GetJsonPatchInputFormatter());
        });
        services.AddCors(options =>
        {
            options.AddPolicy("NUXT",
                            builder =>
                            {
                                builder.WithOrigins("*")
                                       .AllowAnyHeader()
                                       .AllowAnyMethod();
                            });
        });

    }

和 Program.cs 代碼:

using System.Globalization;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}
app.UseDeveloperExceptionPage();

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();
app.UseCors("NUXT");
app.UseAuthorization();
var localizationOptions = new RequestLocalizationOptions()
{
    DefaultRequestCulture = new Microsoft.AspNetCore.Localization.RequestCulture("fa-IR"),
    SupportedCultures = new List<CultureInfo> { new CultureInfo("fa-IR") }
};
app.UseRequestLocalization(localizationOptions);    
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}");

app.Run();

我使用的是 AllowAnyOrigin () 而不是 WithOrigins("*")。 如果您使用它而不是啟動,那么每個程序都應該在一個地方。 cors 通常用於 API,所以也許你也不需要在代碼中添加 withviews

builder.Services.AddCors(o => o.AddPolicy("NUXT", builder =>
{
    builder.AllowAnyOrigin()
           .AllowAnyMethod()
           .AllowAnyHeader();
}));

builder.Services.AddControllers()
.AddNewtonsoftJson(options =>
  options.SerializerSettings.ContractResolver =
        new CamelCasePropertyNamesContractResolver());
.....

var app = builder.Build();

app.UseRouting();

app.UseCors("NUXT");

// app.UseAuthorization();

使用道具

[EnableCors("NUXT")]
public class algoController : ControllerBase{
}

您還可以創建一個 CorsMiddleware,將 header 添加到響應中

    public class CorsMiddleware
    {
        private readonly RequestDelegate _next;

        public CorsMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public Task Invoke(HttpContext httpContext)
        {
            httpContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");
            httpContext.Response.Headers.Add("Access-Control-Allow-Credentials", "true");
            httpContext.Response.Headers.Add("Access-Control-Allow-Headers", "Content-Type, X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Date, X-Api-Version, X-File-Name");
            httpContext.Response.Headers.Add("Access-Control-Allow-Methods", "POST,GET,PUT,PATCH,DELETE,OPTIONS");
            return _next(httpContext);
        }
    }

    public static class CorsMiddlewareExtensions
    {
        public static IApplicationBuilder UseCorsMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<CorsMiddleware>();
        }
    }

並在 de build 后在 program.cs 文件中使用它,例如:

app.UseCorsMiddleware();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM