【发布时间】:2020-02-02 08:55:05
【问题描述】:
我正在尝试将来自 Angular 7 的请求发布到 .NET Core 2.1 中的 REST API 我的拦截器是
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpResponse, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
@Injectable()
export class HttpConfigInterceptor implements HttpInterceptor {
constructor() { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
request = request.clone({
withCredentials: true,
});
return next.handle(request).pipe(
map((event: HttpEvent<any>) => {
if (event instanceof HttpResponse)
{
localStorage.setItem('status','200');
}
return event;
}),
catchError((error: HttpErrorResponse) => {
let data = {};
data = {
reason: error && error.error && error.error.message ? error.error.message : '',
//status: error.status
};
if (data['reason'].length>0){
alert("Error:"+ data['reason']);
}
else{
alert("Error :"+ error.message);
}
return throwError(error);
}));
}
}
我的StartUp.cs的ConfigurationService和Configure方法如下
public void ConfigureServices(IServiceCollection services)
{
services.AddOptions();
services.AddAuthentication(IISDefaults.AuthenticationScheme);
//Get the configuration settings
services.Configure<AppSettings>(Configuration.GetSection("URLSettings"));
String[] origins = Configuration.GetSection("AllowedURLs").Get<AppSettings>().origins;
//Add the services
services.AddTransient<IClaimsTransformation, ClaimsTransformationService>();
//Add Cors
//services.AddCors();
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder
.AllowAnyHeader()
.AllowAnyMethod()
.WithOrigins(origins)
.AllowCredentials()
);
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseCors("CorsPolicy");
//app.UseAuthentication();
//app.UseHttpsRedirection();
app.UseMvc();
}
我在 Angular 中的 POST 方法是
public GenerateCarModels(carIds: number[]) :any {
const body = carIds;
let httpOptions= { headers: new HttpHeaders({ 'Content-Type': 'application/json'})};
const url = `${baseURL}${'/api/GenerateModels/GenerateCarModels'}`;
return this.http.post(url,body,httpOptions);
}
GET 方法有效,拦截器或 API 没有问题,但是当我尝试 POST 得到的值时
Access to XMLHttpRequest at 'http://localhost:53499//api/reports/GenerateCarModels' 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.
Failed to load resource: the server responded with a status of 401 (Unauthorized)
我不确定我在这里做错了什么
我的依赖...
"dependencies": {
"@angular/animations": "~7.2.0",
"@angular/common": "~7.2.0",
"@angular/compiler": "~7.2.0",
"@angular/core": "~7.2.0",
"@angular/forms": "~7.2.0",
"@angular/platform-browser": "~7.2.0",
"@angular/platform-browser-dynamic": "~7.2.0",
"@angular/router": "~7.2.0",
....
....
....
}
能否请您指出我在标题或任何内容中缺少的内容?我已经允许 localhost:4200 在源中,正如我所说的其他 GET 方法工作正常。 谢谢
编辑:当我在后台运行 Fiddler 时,它可以捕获数据。
【问题讨论】:
-
你能显示 appsettings.json 吗?
-
嗨@levent { ' "Logging": { "LogLevel": { "Default": "Warning" } }, "AllowedHosts": "*", "AppSettings": { "origins": [ "localhost:4200"] } }' 这是我的 appSettings.json
-
你调试过 ConfigureServices 方法来检查 origins 变量吗?您的配置键
"AllowedHosts"但您尝试使用"AllowedURLs"读取。 -
@levent .. 感谢您发现它,但我使用“origins”和“withOrigins”一起驱动,AllowedHosts .. 可以删除。更改为匿名并为 POST 方法包含一个“内容类型”。我认为您在标题中至少需要其中一个并且它有效。 (不幸的是,我想发布答案,但由于某种原因 Stackoverflow 不允许我发布答案,我之前没有回答任何问题)
标签: javascript c# angular typescript asp.net-core