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

前端 未结 2 1972
醉酒成梦
醉酒成梦 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 Get() {
          return new string[] { "value1", "value2" };
        }
    ...
    

提交回复
热议问题