.NET Core 3.0中的CORS [英] CORS in .NET Core 3.0

查看:200
本文介绍了.NET Core 3.0中的CORS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在.NET Core 3.0中开发了Web API,并且正在通过React.js进行发布.

I have Web API developed in .NET Core 3.0 and am POSTing through React.js.

在控制器中:

 [Route("api/[controller]")]
    [ApiController]
    public class AuthController : ControllerBase
    {
        [HttpPost, Route("login")]
        [EnableCors()]
        public async Task<IActionResult> Login([FromBody]User user)
        {
            //code implementation
            return Ok(new { Status = "OK" });
        }
    }

在启动中:

public class Startup
    {
        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();
            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();
            });
        }
    }

在React.js中

const data = {
              UserName: "jack",
              Password: "def@123"
            };

            axios
              .post("https://localhost:44369/api/auth/login", {
                body: JSON.stringify(data),
                headers: {
                  "Content-Type": "application/json"
                }
              })

但是我得到以下错误:

OPTIONS https://localhost:44369/api/auth/login 415

Access to XMLHttpRequest at 'https://localhost:44369/api/auth/login' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

PS:请知道我已经尝试了其他各种方法,但是仍然会遇到一些或其他CORS错误.

PS: please know that I have tried various other approaches but keep getting some or the other CORS error.

推荐答案

我能够使其工作如下:

在控制器中:

[Route("api/[controller]")]
    [ApiController]
    public class AuthController : ControllerBase
    {
        [HttpPost, Route("login")]
        [EnableCors()]        
        public async Task<IActionResult> Login(User user)
        {
            //code implementation
            return Ok(new { Status = "OK" });
        }
    }

在启动中:

 public class Startup
    {
        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.AddDefaultPolicy(
                    builder =>
                    {
                        builder.WithOrigins("http://localhost:3000").AllowAnyHeader().AllowAnyMethod();
                    });
            });
            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();
            });
        }
    }

在React.js中:

In React.js :

const data = {
              UserName: "jack",
              Password: "def@123"
            };


axios.post("https://localhost:44392/api/auth/login", data);

这篇关于.NET Core 3.0中的CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆