这是我第一次使用Filter
,但无法正常工作。这是一个非常简单的例子。什么都没有添加到响应头,并且在过滤器类中没有命中断点。我希望这是一个全局过滤器。我想念什么或做错什么了?
过滤器:
public class TestFilter : IResultFilter
{
public void OnResultExecuted(ResultExecutedContext context)
{
throw new NotImplementedException();
}
public void OnResultExecuting(ResultExecutingContext context)
{
var headerName = "OnResultExecuting";
context.HttpContext.Response.Headers.Add(
headerName, new string[] { "ResultExecutingSuccessfully" });
}
}
STARTUP.CS
public void ConfigureServices(IServiceCollection services)
{
var logger = _loggerFactory.CreateLogger<Startup>();
services.AddCors();
services.AddMvc(options =>
{
options.Filters.Add(new TestFilter());
});
}
控制器方法:
[HttpGet("", Name = "search")]
[ProducesResponseType(typeof(PagedResult<SearchViewModel>), (int)HttpStatusCode.OK)]
public async Task<IActionResult> Get()
答案 0 :(得分:2)
为了让javascript在发出跨域请求时读取响应标头,您需要在CORS
应用中建立exposes某些标头到客户端的ASP.NET Core
策略
services.AddCors(options =>
{
options.AddPolicy("ResultHeader", policy =>
{
policy
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.WithExposedHeaders("OnResultExecuting"); //headers to be exposed
});
});
您在全球范围内使用它
app.UseCors("Default");
或仅用于特定操作/控制器
[HttpGet("", Name = "search")]
[ProducesResponseType(typeof(PagedResult<SearchViewModel>), (int)HttpStatusCode.OK)]
[EnableCors("ResultHeader")] //enabling cors requests
public async Task<IActionResult> Get()