I have a several models that share an interface, it looks like
public interface IRequest {
public string RequestId { get; set; }
}
An example of a model that implements this look like
public class CatRequest : IRequest {
public string RequestId { get; set; }
public string Name { get; set; }
I have a CatController that looks like
public class CatController: ControllerBase {
[HttpPost]
public IActionResult AddCat([FromBody] cat) {
// call database and add cat to db
}
}
Knowing fully well that several things can go wrong in the database operation, I have a global exception filter that works and it looks like
public void OnException(ExceptionContext context) {
// create a proper error response message
var error = new ErrorResponse() {
ResponseCode = 400,
RequestId = 2, // HERE IS THE SPOT, I WANT TO READ RequestId from the RequestBody or Model without re-reading the request
// The solution below works, but only when it is a custom exception where I had previously manually added the Data entry
// RequestId = context.Exception.Data["RequestId"]?.ToString()
};
context.Result = new JsonResult(error);
}
Can I get a better implementation?
Thanks.