I've a need to write exception filter for couple of controllers in .NET 6 and for that i've written below and when i do a postman i always get Error: Aborted which is weird
Code:
public class TestFilterAttribute : ExceptionFilterAttribute
{
public override async void OnException(ExceptionContext context)
{
var info = { } //serialized object
context.HttpContext.Response.ContentType = "appication/json";
context.HttpContext.Response.StatusCode = 400;
await context.HttpContext.Response.WriteAsync(info);
}
}
Registered:
services.AddSingleton<TestFilterAttribute>();
Decorated [TestFilter] on my api controller when i intentionally throw exception to check, i always get site cannot be reached. Same logic i've tried in middleware i properly get response in json with expected status code
Check this document related
You could try as below:
public class TestFilterAttribute : ExceptionFilterAttribute
{
public override async void OnException(ExceptionContext context)
{
context.Result = new BadRequestObjectResult(someobj);
}
}
Result:
Since you're trying with an attribute,you don't have to regist it in IServiceCollection
services.AddSingleton<TestFilterAttribute>();
You could check this document about child classes of ObjectResult