简体   繁体   English

Angular POST and .NET Core WEB Api - 401 Unauthorized error / CORS

[英]Angular POST and .NET Core WEB Api - 401 Unauthorized error / CORS

I have separate projects for front-end (Angular) and back-end (.NET Core WEB Api).我有前端(Angular)和后端(.NET Core WEB Api)的单独项目。 I have been setup the CORS as well the windows AD authentification.我已经设置了 CORS 以及 windows AD 身份验证。 All that is working well for GET calls, but I am having issues with the POST.所有这些都适用于 GET 调用,但我遇到了 POST 问题。 I am getting following error.我收到以下错误。

OPTIONS http://localhost:50000/api/data/Update 401 (Unauthorized)
Access to XMLHttpRequest at 'http://localhost:50000/api/data/Update' from origin 'http://localhost:4200' 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.
Error: Http failure response for http://localhost:50000/api/data/Update: 0 Unknown Error

user.component.ts用户.component.ts

update(data: NgForm) {
if (data.form.valid) {
  this.service.update(data.value)
    .subscribe(
      res => {
        console.log('Result: ' + res);
      },
      err => {
        console.log('Error: ' + err.message);
    });
  }
}

service.ts服务.ts

headerOptions = new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded', 'Access- 
Control-Allow-Origin': '*' });

update(data: Form) {
  return this.http.post(this.apiUrl + '/data/Update', data, { headers: this.headerOptions });
}

Controller Controller

[HttpPost("[action]")]
public string Update([FromForm] User data)
  {
    if (data != null)
  {
    return "Ok";
  }
    else
  {
    return "Data is null";
  }
}

CORS extension CORS 扩展

    public static void ConfigureCors(this IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy", 
                builder => builder
                .WithOrigins("http://localhost:4200")
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials());
        });
    }

I also have the interceptor inside Angular which is sending "withCredentials: true" for all calls.我在 Angular 中也有拦截器,它为所有调用发送“withCredentials:true”。

Have in mind that all my GET calls are working without issues, I only have problems with the POST.请记住,我所有的 GET 调用都没有问题,我只有 POST 有问题。 If I change the method on Angular side from POST to GET, the Update method from back-end is getting called without issues...如果我将 Angular 端的方法从 POST 更改为 GET,则后端的 Update 方法将被调用而没有问题...

I was able to hit my controller and POST data after I did following changes:在进行以下更改后,我能够访问我的 controller 和 POST 数据:

  1. Changed controller attribute from "FromForm" to "FromBody" (thanks to Daniel note about it).将 controller 属性从“FromForm”更改为“FromBody”(感谢 Daniel 对此的说明)。
  2. Changed angular post method to the following将 angular 后置方法更改为以下

     headerOptions = new HttpHeaders({ 'Content-Type': 'application/json' }); update(data) { return this.http.post(this.apiUrl + '/data/Update', JSON.stringify(data), { headers: this.headerOptions }); }
  3. Set "anonymousAuthentication: true" inside my launchSettings.json.在我的launchSettings.json 中设置“anonymousAuthentication: true”。

  4. On this stage I had an issue because my user was null on application start, so I had to implement a new middleware found on this question ntlm anon in order to handle non-authenticated user on app start.在这个阶段我遇到了一个问题,因为我的用户在应用程序启动时是 null,所以我必须实现在这个问题ntlm anon上找到的新中间件,以便在应用程序启动时处理未经身份验证的用户。

  5. Call middleware inside Configure (Startup.cs), just pay attention on the order.在Configure(Startup.cs)里面调用中间件,注意顺序。 Here is mine:这是我的:

    app.UseCors("CorsPolicy");
    app.UseAnonMiddleware();
    app.UseAdMiddleware();
    app.UseMvc();

And thats it.就是这样。

Different ports are exactly the same as different applications, therefore your WebApi should allow CORS like不同的端口与不同的应用程序完全相同,因此您的 WebApi 应该允许 CORS 像

 [EnableCors(origins: "http://localhost:4200", headers: "*", methods: "*")]
    public class TestController : ApiController
    {
        // Controller methods not shown...
    }

However, if this is the same application and all you want is that all of the work through the same port then what I think you need to do is:但是,如果这是同一个应用程序并且您想要的只是所有工作都通过同一个端口,那么我认为您需要做的是:

Add Microsoft.AspNetCore.SpaServices.Extensions nuget package.添加 Microsoft.AspNetCore.SpaServices.Extensions nuget package。

And then configure in you Startup.cs the Angular Cli like:然后在 Startup.cs 中配置Angular Cli ,如:

app.UseStaticFiles();
app.UseSpaStaticFiles();

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

            app.UseSpa(spa =>
            {
                spa.Options.SourcePath = "ClientApp";

                if (env.IsDevelopment())
                {
                    spa.UseAngularCliServer(npmScript: "start");
                }
            });

Important :重要

To learn more about options for serving an Angular SPA from ASP.NET Core, see https://go.microsoft.com/fwlink/?linkid=864501要了解有关从 ASP.NET 内核提供 Angular SPA 的选项的更多信息,请参阅https://go.microsoft.com/fwlink/?linkid=86450

This allows you to have if you want angular running on separate port or the same port as your .net core app.如果您希望 angular 在单独的端口或与您的 .net 核心应用程序相同的端口上运行,这允许您拥有。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Azure SignalR on.Net Core Web API and Angular 12 facing 401 Unauthorized Error - Azure SignalR on .Net Core Web API and Angular 12 facing 401 Unauthorized Error Angular MSAL AD 401 在 Angular App 中未经授权,但在 Postman 中 200 Ok - ASP.NET Core Web API - Angular MSAL AD 401 Unauthorized in Angular App but 200 Ok in Postman - ASP.NET Core Web API 对.NET Web API的Angular 6跨域POST请求返回401(未经授权) - Angular 6 cross domain POST request to .NET Web API returns 401 (Unauthorized) 在.net Core Web API和angular 6中启用CORS - Enabling CORS in .net core Web api and angular 6 Web API 2:POST上的随机401未授权 - Web API 2: Random 401 unauthorized on POST Angular 2 -POST 401 未经授权 - Angular 2 -POST 401 Unauthorized Angular 2 http发布到.Net Core Web Api 500错误 - Angular 2 http post to .Net Core Web Api 500 error Error in HTTP Post from Angular into Web API .NET Core - Error in HTTP Post from Angular into Web API .NET Core angular http post error 415 .net core web api - angular http post error 415 .net core web api ASP.NET Core 3.1 Web API 中的“授权失败。AuthenticationScheme:AzureADJwtBearer 受到挑战” - 401 Unauthorized - "Authorization failed. AuthenticationScheme: AzureADJwtBearer was challenged" in ASP.NET Core 3.1 Web API - 401 Unauthorized
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM