You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

启用Windows身份验证的ASP.NET Core POST请求遇CORS错误

Windows认证下POST请求CORS错误排查求助

已完成的配置操作

  • 启用Visual Studio的Windows Authentication设置
  • 修改launchSetting.json文件:
{
  "iisSettings": {
    "windowsAuthentication": true,
    "anonymousAuthentication": false,
    "iisExpress": {
      "applicationUrl": "http://localhost:40825",
      "sslPort": 44361
    }
  }
}
  • 前端Angular请求中设置withCredentials: true:
return this.http.post(`${this.url}/ResolveSnOPLoad?snopid=${proc.snOP.id}`, {},{ withCredentials: true })
  .pipe(
    map(resp => {
      let snop = <VPASnOPModel>resp;
      this.setSnOPInProc(proc, snop, false);
      return snop;
    })
  );

问题现象

GET请求完全正常,但所有POST请求均触发CORS错误。

后端关键配置

Startup.cs 配置

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

    services.AddMemoryCache();
    
    services.AddCors(options => options.AddDefaultPolicy(
        builder =>
        {
            builder.WithOrigins("http://localhost:4200");
            builder.AllowAnyHeader();
            builder.AllowAnyMethod();
            builder.AllowCredentials();
        })
    );

    services.AddTransient<IEmailSenderService, EmailSenderService>();
    services.AddTransient<INegotiationService, NegotiationService>();
    services.AddTransient<INegotiationLinesService, NegotiationLinesService>();
    services.AddTransient<IRFQLinesService, RFQLinesService>();
    services.AddTransient<INotificationQueueService, NotificationQueueService>();

    services.AddSingleton<IConfiguration>(Configuration);
    DAL.DBAccess.ConnectionString = Configuration.GetConnectionString("VPADB");
    DAL.VPAServiceAccess.WS_VPA_Endpoint_URL = Configuration.GetConnectionString("HPOLoadWS");

    services.AddMemoryCache();
    services.AddSignalR();
    services.AddControllers();
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "VPARestfulService", Version = "v1" });
    });

    services.Configure<FormOptions>(o => {
        o.ValueLengthLimit = int.MaxValue;
        o.MultipartBodyLengthLimit = int.MaxValue;
        o.MemoryBufferThreshold = int.MaxValue;
    });

    services.AddAuthorization(options =>
    {
        options.AddPolicy("AllUsers", policy => policy.RequireAuthenticatedUser());
    });
    services.AddAuthentication(IISDefaults.AuthenticationScheme);
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseDeveloperExceptionPage();
    app.UseSwagger();
    app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "VPARestfulService v1"));

    app.UseHttpsRedirection();

    app.UseStaticFiles();
    app.UseStaticFiles(new StaticFileOptions()
    {
        FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"StaticFiles")),
        RequestPath = new PathString("/StaticFiles")
    });

    app.UseRouting();
    app.UseCors();

    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
        endpoints.MapHub<notificationHub>("/notification");
    });
}

控制器代码

[ApiController]
[Route("api/[controller]")]
[Authorize]
public class VPAController : Controller

web.config 配置

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.web>
        <authentication mode="Windows" />
        <authorization>
            <allow verbs="OPTIONS" users="*"/>
            <deny users="?" />
        </authorization>
    </system.web>

    <appSettings>
        <!--The license context used-->
        <add key="EPPlus:ExcelPackage.LicenseContext" value="NonCommercial" />
    </appSettings>
    <system.webServer>
        <handlers>
            <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
        </handlers>
        <aspNetCore requestTimeout="00:20:00" forwardWindowsAuthToken="true" processPath="dotnet" arguments=".\VPARestfulService.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
        <modules runAllManagedModulesForAllRequests="true">
            <remove name="WebDAVModule"/>
            <!-- ADD THIS -->   
        </modules>
        <security>
            <requestFiltering>
                <requestLimits maxAllowedContentLength="1048576000" />
            </requestFiltering>
        </security>
        <httpProtocol>
            <customHeaders>
                <!-- <add name="Access-Control-Allow-Origin" value="*" /> -->
                <add name="Access-Control-Allow-Methods" value="GET,PUT,POST,DELETE,OPTIONS,HEAD" />
                <add name="Access-Control-Allow-Headers" value="Content-Type, Accept"/>
            </customHeaders>
        </httpProtocol>
    </system.webServer>
</configuration>

已尝试的方案

  • 调整Startup.cs中的CORS配置(包括尝试AllowAnyOrigin、设置预检缓存时长等)
  • 给控制器添加CORS属性
  • 前端设置withCredentials: true

但POST请求仍持续出现CORS错误,求可行解决方案。

内容的提问来源于stack exchange,提问作者Nir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 12:20:02