问题
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