I have an ASP.NET MVC action that returns a model to the user.
But if the data is not found I want to return NotFound. ASP.NET MVC doesn't like it since the return type is of that model.
How can I achieve that?
I have an ASP.NET MVC action that returns a model to the user.
But if the data is not found I want to return NotFound. ASP.NET MVC doesn't like it since the return type is of that model.
How can I achieve that?
On
You could build an exception handler and set that as middleware to convert a specific exception to a 404 response, then just throw that exception from your code (or have the middleware catch an exception that may be thrown anyway).
Exception handler would look like this:
public class ExceptionHandler : IMiddleware
{
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
try
{
await next(context);
}
catch (KeyNotFoundException e) // Or whatever exception you want to use
{
context.Response.StatusCode = StatusCodes.Status404NotFound;
await context.Response.WriteAsync(e.Message); // Or nothing, whatever
}
}
}
Then use it as part of the request pipeline like
app.UseMiddleware<ExceptionHandler>();
Then whenever you throw that exception, it will be returned to the caller as a 404.
Edit: What's with the downvotes at least tell me why