0

I run my solution in webApi net.core, and angular , and iis. I success to pass login function(get). but update function (post), I get error:

Access to XMLHttpRequest at 'http://localhost:8080/api/Test/UpdateId' from origin 
'http://localhost:3400' has been blocked by CORS policy: Response to preflight request doesn't 
pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

localhost:8080 - i get from IIS server. localhost:3400 - i get from angular.

my controller:

[TypeFilter(typeof(PermissionFilter), Arguments = new object[] { Modules.Employees, Permissions.Edit, Permissions.Add })]
[HttpPost]
[Route("api/Test/UpdateId")]
public ActionResult<IdModel> UpdateId([FromBody]IdModel idModel)
    { //some code...
    }

Startup.cs:

"AllowSpecificOrigin": "http://localhost:3400"

public void ConfigureServices(IServiceCollection services) {
     services.AddCors(options =>
        {
            options.AddPolicy("AllowSpecificOrigin",
                builder => builder.WithOrigins(Configuration.GetValue<string>("AllowSpecificOrigin"))
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials());
        });
}


public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
            app.UseAuthentication();
      
        if (env.IsDevelopment())
        {      
            app.UseCors("AllowSpecificOrigin");
            app.UseDeveloperExceptionPage();
            app.Use((corsContext, next) =>
                            {
                            corsContext.Response.Headers["Access-Control-Allow-Origin"] = "*";
                                return next.Invoke();
                            });

            app.UseExceptionHandler(a => a.Run(async context =>
            {
                var feature = context.Features.Get<IExceptionHandlerPathFeature>();
                var exception = feature.Error;
                var result = JsonConvert.SerializeObject(new { hasError = true, message = exception.Message });
                context.Response.ContentType = "application/json";
                context.Response.StatusCode = 200;
                await context.Response.WriteAsync(result);
            }));
            app.UseSession();
            app.UseMvc();
        }
        else
        {
            app.UseStaticFiles();
            app.UseSpaStaticFiles();
            app.UseExceptionHandler(a => a.Run(async context =>
            {
                var feature = context.Features.Get<IExceptionHandlerPathFeature>();
                var exception = feature.Error;

                var result = JsonConvert.SerializeObject(new { hasError = true, message = exception.Message });
                context.Response.ContentType = "application/json";
                context.Response.StatusCode = 200;
                await context.Response.WriteAsync(result);
            }));

            app.UseSession();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action=Index}/{id?}");
            });
            app.UseSpa(spa =>
            {
                spa.Options.SourcePath = "ClientApp";
            });
        }

my angular, and run : npx ng serve --open --port 3400

UpdateEmployee(idModel): any {
return this._http.post('http://localhost:8080/api/Test/UpdateId', idModel);

}

how fix this error? maybe it is IIS?

thank.

h.z.
  • 39
  • 10

1 Answers1

0

I run my solution in webapi .core, and angular, and iis when I try run my function, I get error .No 'Access-Control-Allow-Origin' header is present on the requested resource to specific method

Based on your error description it has clearly appeared that, your request has not been matched because your CORS defination is "AllowSpecificOrigin": "http://localhost:3400" but your request has been sent from http://localhost:8080 that might causing the issue.

In addition, couple of way out there in order to get rid of above error.

1. Configure CORS hearder in http Request:

You can set request header from your angular request to overcome the error. You can do as following:

const headers = { 'Access-Control-Allow-Origin': '*'};

Full Request should be like below:

this._http.post('http://localhost:8080/api/Test/UpdateId', idModel, {
  headers: {
    'Access-Control-Allow-Origin': '*'
  }
})

Note: You check more details here how to add CORS header in angular request..

2. Middleware Order:

In correct middleware order can also cause above exception where CORS configuration might not work as expected. We should use UseCors must be placed after UseRouting, but before UseAuthorization and midddleware order should as following:

enter image description here

Note: Please double check the CORS middleware order here in official document.

3. Server Strict Invoke:

If above steps doesn't work accordingly and the problem still recurrent you could then implement server CORS header invocation. You can do that as following:

app.Use((corsContext, next) =>
            {
                corsContext.Response.Headers["Access-Control-Allow-Origin"] = "*";
                return next.Invoke();
            });

Note: If you still want to know more details on the issue you could check the additional resource here.

Md Farid Uddin Kiron
  • 16,817
  • 3
  • 17
  • 43
  • I try option: 1,3 but it is not work. how I write UseRouting, funtion, it is unknow in my code? I have app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller}/{action=Index}/{id?}"); }); – h.z. May 28 '23 at 09:45
  • Your CORS should place in between Routing and Authentication middleware. app.UseMvc shouldn't impact CORS. By the way, what's your asp.net core version? – Md Farid Uddin Kiron May 29 '23 at 01:41
  • my asp.net core version is 2.2. I still don't succses. – h.z. Jun 28 '23 at 09:29