空响应返回204 [英] Null response returns a 204

查看:146
本文介绍了空响应返回204的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我执行GET请求并且找不到任何数据时,控制器返回204.

My controller returns a 204 when I do a GET request and I don't find any data.

[Route("user/v1/[controller]")]
public class UserLoginController : Controller
{
    [HttpGet]
    public async Task<UserLogin> Get(int userId)
    {
        var userLoginLogic = new UserLoginLogic();

        return await userLoginLogic.GetUserLogin(userId);
    }
}

这仅用于GET请求,POST,PUT,DELETE返回20​​0空响应.这不符合我的招摇定义,该定义为200个响应定义了一个响应,我宁愿保持一致.

This is only for GET requests, POST, PUT, DELETE return a 200 empty response. This messes with my swagger definition which has a response defined for a 200 response, and I would rather be consistent.

如果我通过该控制器提供HTML,但204用于REST API,则204会很好.

The 204 would be fine if I was serving HTML out of this controller but it is for a REST API.

我如何得到它返回200?

How do I get it to return a 200?

推荐答案

使用v2.1 +中的新 ActionResult< T> ,您还可以重构以专门告诉控制器使用以下命令返回Ok 200 Ok()辅助方法

With the new ActionResult<T> in v2.1+ you can also refactor to specifically tell the controller to return Ok 200 using the Ok() helper methods

[Route("user/v1/[controller]")]
public class UserLoginController : Controller {
    [HttpGet]
    public async Task<ActionResult<UserLogin>> Get(int userId) {
        var userLoginLogic = new UserLoginLogic();
        var model = await userLoginLogic.GetUserLogin(userId);
        return Ok(model);
    }
}

但是,如果实际上没有要返回的内容,这可能会产生误导.考虑使用适当的响应状态

however this can be misleading if there is in fact no content to return. Consider using an appropriate response status

[Route("user/v1/[controller]")]
public class UserLoginController : Controller {
    [HttpGet]
    public async Task<ActionResult<UserLogin>> Get(int userId) {
        var userLoginLogic = new UserLoginLogic();
        var model = await userLoginLogic.GetUserLogin(userId);
        if(model == null) return NotFound(); //404
        return Ok(model); //200
    }
}

如果打算不带内容返回200 Ok,请使用

If intent on returning 200 Ok with no content use ControllerBase.Ok() method

创建一个OkResult对象,该对象会产生一个空的Status200OK响应.

Creates a OkResult object that produces an empty Status200OK response.

[Route("user/v1/[controller]")]
public class UserLoginController : Controller {
    [HttpGet]
    public async Task<ActionResult<UserLogin>> Get(int userId) {
        var userLoginLogic = new UserLoginLogic();
        var model = await userLoginLogic.GetUserLogin(userId);
        if(model == null) return Ok(); //200 with no content
        return Ok(model); //200
    }
}

参考 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆