c# - Azure 代理,请求 IIS 托管 API 时出现 CORS 错误

标签 c# azure asp.net-core proxy asp.net-core-webapi

我在 IIS 中托管了一个 WebAPI,现在因为我需要从任何地方访问我的 API,所以我创建了一个 azure 代理,但每次我使用 UI 发出请求时,都会收到此错误: enter image description here

启动.cs

配置服务

services.AddCors(options =>
        {
            options.AddDefaultPolicy(
                builder =>
                {
                    builder
                    .SetIsOriginAllowed((string v) => _ = true)
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowCredentials();
                });
        });

配置

            app.UseSerilogRequestLogging();

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseCors();

        app.UseAuthentication();

        app.UseAuthorization();

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

如果我在 IIS 所在的网络中运行前端代码,而不是调用代理,而是调用 API 的本地主机,它就可以正常工作。

最佳答案

您需要在ConfigureServices中添加mycors规则。更多详情,您可以阅读the offical document .

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>options.AddPolicy("mycors",
             p => p.AllowAnyOrigin())
        );
        services.AddControllersWithViews();
    }

然后在Configure函数中应用mycors

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        //*****apply mycors****

        app.UseCors("mycors"); 

        //*********************


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

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }

我解构了我的两个项目。你可以看源码,我已经实现了跨域功能。

enter image description here

关于c# - Azure 代理,请求 IIS 托管 API 时出现 CORS 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62518597/

相关文章:

c# - DocumentDb DocumentClient 获取前 25 个文档

ssl - AddSigningCertificate 出现 OpenIddict 错误

asp.net-core - 如何在 EF Core 中添加父记录及其子记录

c# - NLog 不写入事件日志 .NET Core 2.1

c# - 使用 javascript 取消所有事件

c# - 将字符串文字分配给 C# 中的字符串

azure - 为什么从 Azure Key Vault 下载的证书与我上传的文件不同

c# - TextChanged/LostFocus/等。 DataGridTextColumn 事件

c# - 如何在 MVC 中的 @Html.ActionLink 中获取更新的文本框更改值

Azure 应用服务环境 - New-AzureRmWebApp 损坏?