简体   繁体   中英

ASP.NET Core API Enabling Cors not working

First time trying to make an api with asp.net core, I am using ASP.NET Core 3.1. I run into this console error when I try to send a GET request:

Access to XMLHttpRequest at 'https://localhost:5001/api/items/1' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. 

I have tried a lot of solutions on this site and from others and they do not seem to be working for me. Here is what I have for my Javascript side:

const sendRequest = async function(url) {
    try {
        let response = await axios.get(url);
        return response;
    } catch (error) {
        console.error(error);
        return [];
    }
};

Here is what I have in Startup.cs

public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy("AllowMyOrigin",
                builder => builder.WithOrigins(
                    "http://localhost:8080/")
                    .WithMethods("POST", "GET", "PUT")
                    .WithHeaders("*")
                    );
            });
            services.AddDbContext<DBContext>(opt =>
            opt.UseSqlServer(Configuration.GetConnectionString("DatabaseName")));
            services.AddControllers();
            
            
        }

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            
            //app.UseAuthentication();
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();
            app.UseCors("AllowMyOrigin");
            //app.UseAuthorization();
            //app.UseAuthentication();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

If this is too little info I will try to clarify, but like I said this is my first time doing something like this that deals with the cors policy.

builder.WithOrigins("http://localhost:8080/")

Please note that the specified URL must not contain a trailing slash ( / ). Please modify the code like below, then check if it works well.

services.AddCors(options =>
{
    options.AddPolicy("AllowMyOrigin",
        builder => builder.WithOrigins(
            "http://localhost:8080")
        .WithMethods("POST", "GET", "PUT")
        .AllowAnyHeader()
        );
});

Please try adding this inside

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM