简体   繁体   中英

How return automaticaly error code 404 Not Found WEB API CORE

Hi i would like to know is there any way to return automatically Not Found() if object is null

For example insetad of this

User user = _userService.GetUserById(int id);

if(user is null)
  return Not FOund();

return Ok(user);

I would like to do like this

User user = _userService.GetUserById(int id);

return Ok(user);

And automaticalyy recive null object and status code 404. Is there any way to implement this?

According to your description, I suggest you could try to use custom filter to achieve your requirement.

You could create a global action filter to check the OKobejctResult value, if the value is null, then you could modify the context result.

More details, you could refer to below codes:

Create filter class:

public class TestActionFilter : IActionFilter
{
     
    public void OnActionExecuted(ActionExecutedContext context)
    {

        if (context.Result.GetType() == typeof(OkObjectResult))
        {
            if (((OkObjectResult)context.Result).Value == null)
            {
                context.Result = new NotFoundResult();
            }
        }

    }

    public void OnActionExecuting(ActionExecutingContext context)
    {

        //throw new NotImplementedException();
    }
}

Register it in startup.cs ConfigureServices method:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers(options => options.Filters.Add(typeof(TestActionFilter)));
    }

Then it will work well.

My test controller action:

    [HttpPost]
    public IActionResult CreateImage(string base64image)
    {
        WeatherForecast ew = null;

        return Ok(ew);

    }

Result:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM