VS2017 Web application CORS: Access-Control-Allow-Origin

前端 未结 2 1866
醉酒成梦
醉酒成梦 2021-01-24 09:04

I\'m using Angular 6+ for a small website presenting a CRUD to a SQL Database. I know Angular is a client-side framewor

相关标签:
2条回答
  • 2021-01-24 09:23

    Based on Glen's answer and this "tutorial" I have managed to get the thing working.

    On my Startup.cs file

    ...
    public void ConfigureServices(IServiceCollection services) {
      services.AddCors();       /* <----- Added this line before de MVC */
      services.AddMvc();
    }
    ...
    public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
      if (env.IsDevelopment()) {
        app.UseDeveloperExceptionPage();
      }
      app.UseCors(builder => builder.WithOrigins("http://localhost:4200")); /* <----- Added this line before de MVC */
      app.UseMvc();
    }
    

    And in my controller file CIEController.cs

    ...    
    namespace CIE_webservice.Controllers {
      [Produces("application/json")]
      [Route("api/CIE")]
      [EnableCors(origins: "http://localhost:4200/", headers: "*", methods: "*")] /* <--- This line remains here or can be added at the action level*/
      public class CIEController : Controller {
        [HttpGet]
        public IEnumerable<string> Get() {
          return new string[] { "value1", "value2" };
        }
    ...
    
    0 讨论(0)
  • 2021-01-24 09:25

    I have similar working in a hobby project, so I can show you what I did to get it working...

    I did this in my Startup.cs

    app.UseCors(options => options.WithOrigins(Configuration["trustedCors"].Split(' ')).AllowAnyMethod().AllowAnyHeader());

    with this in my config file ...

    "trustedCors": "http://localhost:60000 https://localhost:60000 http://glendesktop:60000 https://glendesktop:60000"

    I also remember from my testing that case in important for CORS.

    0 讨论(0)
提交回复
热议问题