[英]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
update(data: NgForm) {
if (data.form.valid) {
this.service.update(data.value)
.subscribe(
res => {
console.log('Result: ' + res);
},
err => {
console.log('Error: ' + err.message);
});
}
}
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 });
}
[HttpPost("[action]")]
public string Update([FromForm] User data)
{
if (data != null)
{
return "Ok";
}
else
{
return "Data is null";
}
}
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 数据:
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 }); }
Set "anonymousAuthentication: true" inside my launchSettings.json.在我的launchSettings.json 中设置“anonymousAuthentication: true”。
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上找到的新中间件,以便在应用程序启动时处理未经身份验证的用户。
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.