프런트 엔드 (Angular)와 백 엔드 (.NET Core WEB Api)에 대한 별도의 프로젝트가 있습니다. CORS와 Windows AD 인증을 설정했습니다. 모든 것이 GET 호출에서 잘 작동하지만 POST에 문제가 있습니다. 다음과 같은 오류가 발생합니다.
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());
});
}
또한 모든 호출에 대해 "withCredentials : true"를 보내는 Angular 내부에 인터셉터가 있습니다.
내 모든 GET 호출이 문제없이 작동한다는 점을 명심하십시오. POST에만 문제가 있습니다. Angular 측의 메서드를 POST에서 GET으로 변경하면 백엔드의 Update 메서드가 문제없이 호출됩니다.
다음 변경 사항을 수행 한 후 컨트롤러 및 POST 데이터를 칠 수있었습니다.
앵귤러 포스트 방식을 다음과 같이 변경
headerOptions = new HttpHeaders({ 'Content-Type': 'application/json'
});
update(data) {
return this.http.post(this.apiUrl + '/data/Update', JSON.stringify(data), {
headers: this.headerOptions });
}
내 launchSettings.json에서 "anonymousAuthentication : true"를 설정합니다.
이 단계에서는 응용 프로그램 시작시 사용자가 null이기 때문에 문제가 발생했기 때문에 앱 시작시 인증되지 않은 사용자를 처리하기 위해이 질문 ntlm anon 에서 찾은 새로운 미들웨어를 구현해야했습니다 .
Configure (Startup.cs) 내에서 미들웨어를 호출하고 주문에주의를 기울이십시오. 다음은 내 것입니다.
app.UseCors("CorsPolicy");
app.UseAnonMiddleware();
app.UseAdMiddleware();
app.UseMvc();
그리고 그게 다야.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다