【发布时间】:2018-04-23 19:32:49
【问题描述】:
我有一个标准的 ASP.NET Core 2 Web 应用程序作为 REST/WebApi。对于我的一个端点,当用户提供错误的搜索/过滤查询字符串参数时,我会返回 HTTP 400。
与 POSTMAN 完美搭配。但是,当我尝试使用我的 SPA 应用程序(实际上是跨域并因此执行 CORS 请求)对此进行测试时,我在 Chrome 中遇到了故障。
向返回 HTTP 200 响应的端点发出 CORS 请求时,一切正常。
看起来我的错误处理没有考虑到 CORS 的东西(即不添加任何 CORS 标头)并且不包括在内。
我猜我搞砸了响应负载管道的东西。
问:有没有一种方法可以更正返回自定义错误处理中的任何 CORS 标头信息,而无需对标头进行硬编码,而是使用在 Startup.cs 中的 Configure/ConfigureServices 方法中设置的标头内容?强>
伪代码..
public void ConfigureServices(IServiceCollection services)
{
... snip ...
services.AddMvcCore()
.AddAuthorization()
.AddFormatterMappings()
.AddJsonFormatters(options =>
{
options.ContractResolver = new CamelCasePropertyNamesContractResolver();
options.Formatting = Formatting.Indented;
options.DateFormatHandling = DateFormatHandling.IsoDateFormat;
options.NullValueHandling = NullValueHandling.Ignore;
options.Converters.Add(new StringEnumConverter());
})
.AddCors(); // REF: https://docs.microsoft.com/en-us/aspnet/core/security/cors#setting-up-cors
... snip ...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
... snip ...
app.UseExceptionHandler(options => options.Run(async httpContext => await ExceptionResponseAsync(httpContext, true)));
app.UseCors(builder => builder//.WithOrigins("http://localhost:52383", "http://localhost:49497")
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod());
... snip ...
}
private static async Task ExceptionResponseAsync(HttpContext httpContext, bool isDevelopmentEnvironment)
{
var exceptionFeature = httpContext.Features.Get<IExceptionHandlerPathFeature>();
if (exceptionFeature == null)
{
// An unknow and unhandled exception occured. So this is like a fallback.
exceptionFeature = new ExceptionHandlerFeature
{
Error = new Exception("An unhandled and unexpected error has occured. Ro-roh :~(.")
};
}
await ConvertExceptionToJsonResponseAsyn(exceptionFeature,
httpContext.Response,
isDevelopmentEnvironment);
}
private static Task ConvertExceptionToJsonResponseAsyn(IExceptionHandlerPathFeature exceptionFeature,
HttpResponse response,
bool isDevelopmentEnvironment)
{
if (exceptionFeature == null)
{
throw new ArgumentNullException(nameof(exceptionFeature));
}
if (response == null)
{
throw new ArgumentNullException(nameof(response));
}
var exception = exceptionFeature.Error;
var includeStackTrace = false;
var statusCode = HttpStatusCode.InternalServerError;
var error = new ApiError();
if (exception is ValidationException)
{
statusCode = HttpStatusCode.BadRequest;
foreach(var validationError in ((ValidationException)exception).Errors)
{
error.AddError(validationError.PropertyName, validationError.ErrorMessage);
}
}
else
{
// Final fallback.
includeStackTrace = true;
error.AddError(exception.Message);
}
if (includeStackTrace &&
isDevelopmentEnvironment)
{
error.StackTrace = exception.StackTrace;
}
var json = JsonConvert.SerializeObject(error, JsonSerializerSettings);
response.StatusCode = (int)statusCode;
response.ContentType = JsonContentType;
// response.Headers.Add("Access-Control-Allow-Origin", "*"); <-- Don't want to hard code this.
return response.WriteAsync(json);
}
干杯!
【问题讨论】:
标签: c# asp.net asp.net-core cors asp.net-core-2.0