【问题标题】:Getting CORS error when CORS is configured and used配置和使用 CORS 时出现 CORS 错误
【发布时间】:2023-01-12 04:50:52
【问题描述】:

我的应用程序有两个组件

  • .NET 7.0 Blazor WASM Web 客户端。 https://本地主机:7139
  • .NET 7.0 MVC 服务器。 https://本地主机:7146

从 webclient 向服务器发送请求时,我遇到了 CORS 错误。该请求是一个空的 POST,在 auth 标头中包含不记名令牌。

服务器已配置 CORS,并调用 UseCors(),所以我希望这应该有效。端点在从 Swagger 调用时工作,在从 Postman 调用时工作。 CORS 错误仅在从我的 Blazor webClient 调用时发生。

服务器:程序.cs

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Identity.Web;
using Microsoft.EntityFrameworkCore;
using Random_Data_Service.DAL;
using Microsoft.Identity.Client;

internal class Program
{
    private static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);

        // Add services to the container.
        var authSection = builder.Configuration.GetSection("AzureAd");
        var cosmosSection = builder.Configuration.GetSection("Cosmos");

        builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddMicrosoftIdentityWebApi(authSection);

        builder.Services.AddCors(option => option
            .AddDefaultPolicy(policy => policy
                .WithOrigins(new[] { "https://localhost:7139/" })
                .AllowCredentials()
                .AllowAnyHeader()
                .AllowAnyMethod()
                ));

        builder.Services.AddControllers();

        builder.Services.AddEndpointsApiExplorer();

        builder.Services.AddSwaggerGen();

        builder.Services.AddDbContext<DataModelContext>(options => options.UseCosmos(
            accountEndpoint: cosmosSection["Url"] ?? "",
            accountKey: cosmosSection["Key"] ?? "",
            databaseName: cosmosSection["DataBase"] ?? ""));


        IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
                    .Create(authSection["ClientId"])
                    .WithTenantId(authSection["TenantId"])
                    .WithClientSecret(authSection["ClientSecret"])
                    .Build();

        var app = builder.Build();

        if (app.Environment.IsDevelopment())
        {
            app.UseSwagger();
            app.UseSwaggerUI();
        }

        app.UseHttpsRedirection();

        app.UseCors();

        app.UseAuthentication();

        app.UseAuthorization();

        app.MapControllers();

        app.Run();
    }
}

服务器:UserController.cs

using Microsoft.AspNetCore.Mvc;

namespace Random_Data_Service.Controllers
{
    [Route("api/[Controller]")]
    [ApiController]
    public class UserController : Controller
    {
        [HttpPost]
        public string Register()
        {
            return "yes";
        }
    }

网络客户端:UserService.cs

namespace BlazorWASM.Services
{
    public class UserService : IUserService
    {
        //Properties
        private readonly HttpClient _httpClient;


        /* Constructor */
        public UserService(HttpClient httpClient)
        {
            _httpClient = httpClient;
        }

        /* Public Methods */
        public async Task RegisterUser()
        {
            var response = await _httpClient.PostAsJsonAsync<string>("api/User/", "test");
        }

        /* Private Methods */

    }

    public interface IUserService
    {
        /* Public Methods */
        Task RegisterUser();

        /* Private Methods */
    }
}

【问题讨论】:

    标签: c# asp.net-mvc cors


    【解决方案1】:

    原来是一个非常简单的错误。不应有斜线尾随允许的来源。

    正确的

    builder.Services.AddCors(option => option
                .AddDefaultPolicy(policy => policy
                    .WithOrigins(new[] { "https://localhost:7139" })
                    .AllowCredentials()
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    ));
    
    

    不正确

    builder.Services.AddCors(option => option
                .AddDefaultPolicy(policy => policy
                    .WithOrigins(new[] { "https://localhost:7139/" })
                    .AllowCredentials()
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    ));
    
    

    【讨论】:

      猜你喜欢
      • 2021-12-20
      • 2017-04-27
      • 1970-01-01
      • 2021-05-09
      • 2020-10-04
      • 2021-09-21
      • 1970-01-01
      • 1970-01-01
      • 2017-04-29
      相关资源
      最近更新 更多