Pur*_*ome 6 c# asp.net cors asp.net-core asp.net-core-2.0
我有一个标准的 ASP.NET Core 2 Web 应用程序充当 REST/WebApi。对于我的一个端点,HTTP 400当用户提供错误的搜索/过滤查询字符串参数时,我返回一个。
与 POSTMAN 配合使用效果很好。但是当我尝试使用我的 SPA 应用程序(实际上它现在跨域并因此执行 CORS 请求)进行测试时,我在 Chrome 中失败了。
对返回HTTP 200响应的端点执行 CORS 请求时,一切正常。
看起来我的错误处理没有考虑到 CORS 的内容(即不添加任何 CORS 标头)并且不包括它。
我猜我搞砸了响应负载管道的东西。
问:有没有办法纠正自定义错误处理中返回的任何 CORS 标头信息,而无需对标头进行硬编码,而是使用在Configure/ConfigureServices方法中设置的标头内容Startup.cs?
伪代码..
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);
}
Run Code Online (Sandbox Code Playgroud)
干杯!
在ExceptionHandler中间件中,在Response传递到您自己的中间件函数之前被清除,如源代码所示:
try
{
await _next(context);
}
catch (Exception ex)
{
// ...
context.Response.Clear();
// ...
await _options.ExceptionHandler(context);
// ..
}
Run Code Online (Sandbox Code Playgroud)
当然,这意味着可能已针对 CORS 设置的任何响应标头也将被清除。
以下代码插入到通用 CORS 系统中,我相信它似乎主要满足您ConfigureServices可以使用配置的要求:
var corsService = httpContext.RequestServices.GetService<ICorsService>();
var corsPolicyProvider = httpContext.RequestServices.GetService<ICorsPolicyProvider>();
var corsPolicy = await corsPolicyProvider.GetPolicyAsync(httpContext, null);
corsService.ApplyResult(
corsService.EvaluatePolicy(httpContext, corsPolicy),
httpContext.Response);
Run Code Online (Sandbox Code Playgroud)
GetPolicyAsync 将策略的名称作为第二个参数 - 如果它为空(如我的示例),它将使用默认策略(如果已设置)。
为了保持重点,我没有在代码示例中包含空检查或任何内容,但这种方法在我构建的测试项目中有效。
这种方法深受Microsoft.AspNetCore.Mvc.Cors 中CorsAuthorizationFilter源代码的影响。
编辑:您没有在示例代码中使用命名策略,但您可以使用以下方法切换到一个:
.AddCors(corsOptions => corsOptions.AddPolicy(
"Default",
corsPolicyBuilder => corsPolicyBuilder
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()));
Run Code Online (Sandbox Code Playgroud)
这使用AddPolicy- 我AddDefaultPolicy在评论中提到过,但看起来这不在当前版本中,因此尚不可用。通过上述更改,您可以UseCors像这样调用:
app.UseCors("Default");
Run Code Online (Sandbox Code Playgroud)
最后的更改是在您的异常处理代码中更新为以下内容:
await corsPolicyProvider.GetPolicyAsync(httpContext, "Default");
Run Code Online (Sandbox Code Playgroud)
为此,您最好使用某种 const 字符串,特别是因为它很可能都从同一个文件中运行。此处的主要更改不再尝试使用默认命名策略,因为我正在 GitHub 上查看尚未发布的当前版本的源代码。
| 归档时间: |
|
| 查看次数: |
843 次 |
| 最近记录: |