1

As shown on the code below, I am sending a post request to a web api created using ASP.NET. The server is an ISS Express.

The error the browser is sending to me is

MainPage.html:1 Access to fetch at 'https://localhost:44346/api/topic' from origin 'null' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response

I have looked at several articles and have found that my issue is that the CORS option in my WEB-API doesn't send back an option that says to allow application/json. From what I understand, the reason this issue is occurring is because my browser and ISS Express are on the same machine so CORS is being triggered. I have looked for resources to help me get the CORS in ASP.NET to include the application/json as an allowed header and have made no headway at all. I also tried disabling the CORS in my browser but I couldn't find an web page that explained how to do it either.

What do I need to do to fix this issue?

JavaScript Code

function SubmitTopic() 
{
//Boilerplate code erased for succinctness
            console.log("Creating Request")
            const request = new Request("https://localhost:44346/api/topic", {
                method: 'POST',
                body: json,
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            console.log(request)

            console.log("Starting POST request to API")
            fetch(request).then(res => {
                if (res.status == 201) {
                    console.log("Successfully added json")
                    console.log("Clearing name and description boxes")
                    name.value = "";
                    description.value = "";
                }
                else {
                    console.error("A problem has occured")
                    alert("Failed to post")
                }
            })
        }

C# - Startup Code

using DSPWHU.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore.Cors;

namespace DSPWHU
{
    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.AddDbContext<EvidenceContext>(opt => opt.UseSqlite("EvidenceList"));
            services.AddDbContext<TopicContext>(opt => opt.UseSqlite("TopicList"));
            
            services.AddControllers();
            services.AddCors(options =>
            {
                options.AddPolicy(name: MyAllowSpecificOrigins,
                                  builder =>
                                  {
                                      builder.AllowAnyOrigin();
                                  });
            });

        }

        // 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(MyAllowSpecificOrigins);
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}
Serge
  • 40,935
  • 4
  • 18
  • 45

1 Answers1

1

Try to replace your service.AddCors() with this:


 services.AddCors(o => o.AddPolicy(MyAllowSpecificOrigins, builder =>
            {
                builder.AllowAnyOrigin()
                       .AllowAnyMethod()
                       .AllowAnyHeader();
            }));

and place it at the top of ConfigureServices section.

Serge
  • 40,935
  • 4
  • 18
  • 45