简体   繁体   中英

Asp.Net Core WebAPI CORS Not working

I am trying to implement the WebAPI Service by using .Net Core and I couldn't manage to set up the CORS working correctly.

I got the main application 'MainApp' and it's going to generate the Invoice on the fly and I want to promote it as the service. This is not a pure WebAPI application. I just want to add this InvoiceController as the WebAPI and there are other Controllers such as HomeController, ProductsController, etc... with views and cshtml.

I got separate Classic WebForm .Net Application which is going to call that InvoiceGeneration Service via Ajax and display values on the website.

When I run my ajax script, I got this famous CORS error.

在此输入图像描述

This is my ajax Get method. It doesn't matter whether I put xhrFields or not. I even changed dataType: 'jsonp' and it still gives me the same error.

$.ajax({
                type: "GET",
                url: 'http://localhost:57012/invoice/test/123',
                dataType: 'json',                
                contentType: 'application/json',
                success: function (data) {                    
                    console.log(data);
                },
                xhrFields: {
                    withCredentials: true
                }
            });

InvoiceController.cs

My Invoice Service is very simple... Just one method which is returning some JSON values.

Since I am using Policy and Claims to determine the security, I put AllowAnonymous attribute. Even though I remove that restriction, it still doesn't work.

public class InvoiceController : Controller
    {        
        [HttpGet]
        [AllowAnonymous]        
        [EnableCors("AllowAll")]
        public async Task<IActionResult> Test(string id)
        {

            return new JsonResult(id);
        }
    }

Startup.cs

I added AllowAll Policy to allow all type of requests.

    public void ConfigureServices(IServiceCollection services)
            {
                services.AddDbContext<DbContexts.PJDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("PJConnection")));

                services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

                services.AddMvc()
                    .AddJsonOptions(o => o.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)
                    .AddJsonOptions(o => o.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver());

                services.AddCors(options => options.AddPolicy("AllowAll", p => p.AllowAnyOrigin()
                                                                .AllowAnyMethod()
                                                                 .AllowAnyHeader()
                                                                 .AllowCredentials()));    


                services.AddAuthorization(options =>
                {
                    options.AddPolicy(Constants.CONST_POLICY_SUPERADMIN, policy => policy.RequireRole(Constants.CONST_ROLE_SUPERADMIN));
                    options.AddPolicy(Constants.CONST_POLICY_STUDENT, policy => policy.RequireRole(Constants.CONST_ROLE_STUDENT, Constants.CONST_ROLE_ADMIN, Constants.CONST_ROLE_SUPERADMIN));
                });
            }

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IOptions<AppSettings> AppSettings)
            {
                loggerFactory.AddConsole(Configuration.GetSection("Logging"));
                loggerFactory.AddDebug();

                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    app.UseExceptionHandler("/Home/Error");
                }

                app.UseStaticFiles();

                if (env.IsProduction())
                {
                    app.UseStaticFiles(new StaticFileOptions()
                    {
                        FileProvider = new PhysicalFileProvider(AppSettings.Value.FilePathToUpload),
                        RequestPath = new PathString("/Files"),
                    });
                }

                app.UseCookieAuthentication(new CookieAuthenticationOptions
                {
                    AuthenticationScheme = "Cookie",
                    LoginPath = new PathString("/Account/Login/"),
                    AccessDeniedPath = new PathString("/Account/Forbidden/"),
                    AutomaticAuthenticate = true,
                    AutomaticChallenge = true
                });

                app.UseCors("AllowAll");
                app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=Home}/{action=Index}/{id?}");
                });
            }

Here is the interesting part.

I created another new .Net Core WebAPI project and copy this CORS Setup to the Startup.cs and InvoiceController to the new project. CORS is working fine and my AJAX can call that method from the new project.

But I don't want to make multiple projects and can't I embed that WebAPI in the existing MVC WebApp Project?

I have seen some tutorials which is running both WebAPIs and MVC Controllers side by side in the same project (obviously they are in the same domain. So, CORS is not a problem for them). Very confusing.

Could you guys please help me with it?

PS. This Html5Rocks tutorial js script doesn't work too.

In my opinion, I don't think there is nothing wrong with JqueryAJAX script. I got another pure WebAPI .Net Core service and I managed to set up the CORS correctly with the same 'AllowAll Policy' code. I can call that service from any cross domain websites by using this simple Jquery script.

$.ajax({
                type: "GET",
                url: 'http://oakapi/staff/byid/2618',
                dataType: 'json',                
                contentType: 'application/json',
                success: function (data) {
                    console.log(data);
                }             
            });

我认为service.AddCors()应该放在service.AddMvc()之前。

set ajax like this:

$.ajax({
            type: "GET",
            url: 'http://oakapi/staff/byid/2618',
            dataType: 'jsonp',                
            contentType: 'application/javascript',
            success: function (data) {
                console.log(data);
            }             
        });

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