'TestController.Post()': not all code paths return a value

不羁岁月 提交于 2020-02-05 04:34:07

问题


I am returning HttpResponseMessage, but still my code complains and throw below error,

'TestController.Post()': not all code paths return a value

What to return here?

public async Task<IHttpActionResult> Post()
    {
        var response = await IsDataValid();
        if (response)
            return Ok(new HttpResponseMessage(HttpStatusCode.OK));
    }

回答1:


You need to add just few more line of code to deal with the above error.

public async Task<IHttpActionResult> Post()
{
    var response = await IsDataValid();
    if (response)
        return Ok(new HttpResponseMessage(HttpStatusCode.OK));
    else
        return NotFound();
}

The else part is important here.




回答2:


If within ApiController, no need to return HttpResponseMessage if returning IHttpActionResult. Use the controller's helper methods.

For example

public async Task<IHttpActionResult> Post() {
    var response = await IsDataValid();
    if (response)
        return Ok();

    return BadRequest();
}


来源:https://stackoverflow.com/questions/58926622/testcontroller-post-not-all-code-paths-return-a-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!