我有一個托管在 Azure 中的 ASP.NET Core Web API。當我嘗試從 Vercell 上托管的 Web 應用程式發出提取請求時,出現以下錯誤:
{myapi enpoint}從源“https:{myapp}//.vercel.app”獲取的訪問已被 CORS 策略阻止:
對預檢請求的回應未通過訪問控制檢查:沒有“Access-Control-Allow-Origin”標頭存在于請求的資源。如果不透明回應滿足您的需求,請將請求的模式設定為“no-cors”以在禁用 CORS 的情況下獲取資源。
這是我的Startup.cs檔案:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Cors;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using Pomelo.EntityFrameworkCore.MySql;
using System.Threading.Tasks;
using ctsapi.Services;
using Jose;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using ctsapi.Models;
using Newtonsoft.Json.Linq;
using Microsoft.AspNetCore.Http;
using System.Net;
namespace ctsapi
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowAllOrigins", builder =>
{
builder.AllowAnyOrigin();
builder.AllowAnyMethod();
builder.AllowAnyHeader();
});
});
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "ctsapi", Version = "v1" });
//c.IncludeXmlComments(XmlCommentsPath.XmlCommentsFilePath);
});
var jwtSection = Configuration.GetSection("JWTSettings");
services.Configure<JWTSettings>(jwtSection);
//to validate the token which has been sent by clients
var appSettings = jwtSection.Get<JWTSettings>();
var key = Encoding.ASCII.GetBytes(appSettings.SecretKey);
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
x.RequireHttpsMetadata = true;
x.SaveToken = true;
x.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
});
services.AddAuthorization(options =>
{
options.AddPolicy(Policies.Admin, Policies.AdminPolicy());
options.AddPolicy(Policies.ShopKeeper, Policies.ShopKeeperPolicy());
options.AddPolicy(Policies.User, Policies.UserPolicy());
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseDefaultFiles();
app.UseStaticFiles(); // dodanie wwwroot
//if (env.IsDevelopment())
//{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "ctsapi v1"));
//}
app.UseHttpsRedirection();
app.UseRouting();
app.Use(async (context, next) =>
{
await next();
if (context.Response.StatusCode == (int)HttpStatusCode.Unauthorized)
{
// "Token Validation Has Failed. Request Access Denied"
context.Response.ContentType = "application/json";
await context.Response.WriteAsync(new ErrorDto()
{
StatusCode = 401,
Message = "Token Validation Has Failed. Request Access Denied"
}.ToString());
}
});
app.UseCors("AllowAllOrigins");
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
知道為什么會這樣嗎?
我的網路應用程式框架是 Next.js。
這是我的 Azure 配置:
- 默認部署組態檔(在具有 F1 層的 Windows 機器上托管的 WebApp)
- 我什
web.config至將檔案更改為始終發送所需的標頭
uj5u.com熱心網友回復:
嘗試使用這種語法
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(o => o.AddPolicy("AllowAnyOrigin",
builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
.....
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
.....
// app.UseRouting();
app.UseCors("AllowAnyOrigin");
// app.UseAuthorization();
// app.UseEndpoints(..
}
確保 UseCors 應該在 Configure 方法的末尾但在 UseAuthorizaton 之前。AddCors 應位于配置服務的頂部。
uj5u.com熱心網友回復:
所以看起來后端方面的框架只是有一些問題(我不知道如何描述)。當我重新啟動我的 PC 然后重建我的應用程式時,一切正常。
謝謝大家的每一條評論??
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/351534.html
