How to return correct status code when enumeration

2019-08-08 23:09发布

NOTE: The following problem happens only during testing of the controller. Here is refined question How to properly integration test Web Api controller with IEnumerable results?

Is there any way to avoid calling ToList method but still return correct status code in case of exception from deferred LINQ execution to keep controllers as simple as possible?

E.g. I have such API endpoint:

public class EntityController : ApiController
{
    ...
    public IHttpActionResult Get()
    {
        return Ok(Session.Query<Entity>());
    }
}

Above code will always return successful status code, but with ToList it will not be successful in case of any trouble executing the query.

public class EntityController : ApiController
{
    ...
    public IHttpActionResult Get()
    {
        return Ok(Session.Query<Entity>().ToList());
    }
}

The reason why it work like that is clear, but is there any smarter way to return proper status code and keep controller simple?

1条回答
叛逆
2楼-- · 2019-08-08 23:29

You could debug the action, then look what exception gets thrown.

Then you can easily try-catch this line of code and if if fails, you give something different then 500 back.

try
{
    return //...;
}
catch (//your Exception)
{
    return //... As Example BadRequest or something different
}

Hope it helps.

查看更多
登录 后发表回答