'How to customize all response in .Net Core?
Im using .Net Core to write a json api server, so I need customize all response to like:
public class Result {
public int Code { get; set; }
public string Message { get; set; }
public object Data { get; set; }
}
as
{
"code": 1,
"message": "success",
"data": ...
}
For some response(or exception), I can using IResultFilter
(or IExceptionFilter
) to format the response body:
public class ResultFilter : IResultFilter {
public void OnResultExecuted(ResultExecutedContext context) {
}
public void OnResultExecuting(ResultExecutingContext context) {
context.Result = new JsonResult(new Result());
}
}
But in some case(like 400
, 404
and 415
), it would not be enter the Filter
and will return directily.
I was try to use Middleware, but it could not hold them too.
So I want to catch all error and format it like ExceptionFilter
, how can I do?
Solution 1:[1]
ExceptionFilter
can only handle server-side exceptions. Do you find that the case can't be enter the Filter
are all 4xx
error, They are all client-side exceptions, So you can use UseStatusCodePages
to handle these exceptions:
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseStatusCodePages(async statusCodeContext =>
{
// using static System.Net.Mime.MediaTypeNames;
statusCodeContext.HttpContext.Response.ContentType = "application/json";
switch (statusCodeContext.HttpContext.Response.StatusCode)
{
await statusCodeContext.HttpContext.Response.WriteAsync(
JsonConvert.SerializeObject(result415)
);
break;
case 404:
var result = new Result {
Code = 404,
Message = "Not Found",
Data = "......"
};
await statusCodeContext.HttpContext.Response.WriteAsync(
JsonConvert.SerializeObject(result)
) ;
break;
}
});
//......
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |