这是我第一次使用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()
为了让javascript在发出跨源请求时读取响应头,你需要在CORS
应用程序中构建ASP.NET Core
策略,exposes某些头到客户端
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()