简体   繁体   English

在 asp.net 内核中启用 CORS

[英]Enabling CORS in asp.net core

I created a simple api in .net core and trying to access that from react app, I get a CORS error.我在 .net 核心中创建了一个简单的 api 并尝试从反应应用程序访问它,我收到 CORS 错误。 I enabled cors by following CORS with default policy and middleware section on我按照 CORS 启用了 cors 并启用CORS with default policy and middleware部分

https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1 https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1

still I get cors error in my react app.我的反应应用程序中仍然出现 cors 错误。 not exactly sure where I am getting it wrong.不完全确定我在哪里弄错了。

.net core api .net核心api

namespace React_NalONE_API
{
    public class Startup
    {
        readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
        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(name: MyAllowSpecificOrigins,
                //                 builder =>
                //               {
                //                 builder.WithOrigins("http://localhost/*",
                //                                   "https://localhost/*");
                //         });

                options.AddDefaultPolicy(
                builder =>
                {
                    builder.WithOrigins("http://localhost/*",
                                        "https://localhost/*");
                });
            });
            services.AddControllers();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseCors();

            app.UseAuthorization();

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

React app反应应用

 componentDidMount () {
        console.log("The component is now mounted")
        this.setState({loading : true})
        fetch('https://localhost:44391/agency')
        .then(data => data.json())
        .then(data => this.setState({data, loading : false}))
      }

error错误

Access to fetch at 'https://localhost:44391/agency' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Your help is much appreciated Thanks R非常感谢您的帮助谢谢 R

From the document , you could know that:文档中,您可以知道:

Note: The specified URL must not contain a trailing slash (/).注意:指定的 URL 不得包含尾部斜杠 (/)。 If the URL terminates with /, the comparison returns false and no header is returned.如果 URL 以 / 结束,则比较返回 false 并且不返回 header。

For your requirement,it seems you want to allow CORS requests from all origins with any scheme ( http or https ),I suggest that you could use AllowAnyOrigin :根据您的要求,您似乎希望通过任何方案( httphttps )允许来自所有来源的 CORS 请求,我建议您可以使用AllowAnyOrigin

 services.AddCors(options =>
        {
            options.AddDefaultPolicy(
                builder =>
                {
                    builder.AllowAnyOrigin();
                });
        });

Reference:参考:

Another way is to change like below:另一种方法是更改如下:

 services.AddCors(options =>
        {
            options.AddDefaultPolicy(
                builder =>
                {
                    builder.WithOrigins("https://localhost:44391",
                                        "http://localhost:44391");
                });
        });

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

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