ASP.NET MVC controller to either return error or model

122 Views Asked by At

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?

2

There are 2 best solutions below

5
Jeremy Stevens On
public ActionResult GetModel(int id)
{
    // Retrieve the model from your data source
    var model = GetDataFromSource(id);

    if (model == null)
    {
        // If the model is not found, return a NotFound response
        return NotFound();
    }

    // If the model is found, return it as a ViewResult or any other appropriate action result type
    return View(model);
}
3
Squirrelkiller 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