locked
Issues with Ajax calls RRS feed

  • Question

  • User1308320631 posted

    Hi.

    I have a .net core api which works before locally. However, when deploying I get a "no Access-Control-Allow-Origin" header present issue.

    I have Cors added in Startus.cs:

    services.AddCors(options =>

    {
    options.AddPolicy("CorsPolicy",
    builder => builder.AllowAnyOrigin()
    .AllowAnyMethod()
    .AllowAnyHeader()
    .AllowCredentials());
    });

    If I call directly, I get a json result perfectly but Ajax gives me this error. On another pc, it gives ERR_CONNECTION_RESET.

    The Controller method is:

    [HttpPost]
    public List<ProductViewModel> GetGenerics(string searchText)
    {
    List<ProductViewModel> lst = new List<ProductViewModel>();
    ProModel prod = new ProViewModel() { Name = "test", IsOrder = true };
    lst.Add(prod);
    return lst;

    }

    Can anyone help here?

    Thanks

    Thursday, August 24, 2017 4:12 PM

All replies

  • User-832373396 posted

    Hi full,

    It seems that you missed some steps , and please check this cos as shown below:

       public void ConfigureServices(IServiceCollection services)
            {
                // Add framework services.
                services.AddMvc();
               
                services.AddCors(options =>
    
                {
                    options.AddPolicy("CorsPolicy",
                    builder => builder.AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials());
                });
              
        }
    
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
            {
                loggerFactory.AddConsole(Configuration.GetSection("Logging"));
                loggerFactory.AddDebug();
    
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                    app.UseBrowserLink();
                }
                else
                {
                    app.UseExceptionHandler("/Home/Error");
                }
    
                app.UseStaticFiles();
                app.UseCors("CorsPolicy");

    in controller:

       [HttpPost]
            [EnableCors("CorsPolicy")]
            public List<ProductViewModel> GetGenerics(string searchText)
            {
                List<ProductViewModel> lst = new List<ProductViewModel>();
                ProModel prod = new ProViewModel() { Name = "test", IsOrder = true };
                lst.Add(prod);
                return lst;
    
            }

    Resource :https://docs.microsoft.com/en-us/aspnet/core/security/cors 

    With regards,

    Angelina Jolie

    Friday, August 25, 2017 8:21 AM