简体   繁体   English

Azure 代理,CORs 请求时出错 IIS 托管 Z8A5DA52ED126447AD359E70C0572

[英]Azure Proxy, CORs error when request IIS hosted api

I hosted a web api in IIS and now because i need to access my api from everywhere i create an azure proxy but every time that i use my UI to make a request, i get this error I hosted a web api in IIS and now because i need to access my api from everywhere i create an azure proxy but every time that i use my UI to make a request, i get this error 在此处输入图像描述

startup.cs启动.cs

ConfigureServices配置服务

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

Configure配置

            app.UseSerilogRequestLogging();

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseCors();

        app.UseAuthentication();

        app.UseAuthorization();

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

if i run my front-end code in the network where the IIS is and instead of calling the proxy call the api localhost it works just fine.如果我在 IIS 所在的网络中运行我的前端代码,而不是调用代理调用 api localhost 它工作得很好。

You need add mycors rule in ConfigureServices.您需要在 ConfigureServices 中添加mycors规则。 For more details, you can read the offical document .更多详情,您可以阅读官方文档

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

Then apply mycors in Configure function.然后在Configure function 中应用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?}");
        });
    }

I depoly my two project.我解散了我的两个项目。 You can see source code, and I have achieve cross-domain functionality.可以看源码,我已经实现了跨域功能。

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM