如何返回正确的状态code时的IEnumerable枚举失败。 ASP.NET的WebAPI [英] How to return correct status code when enumeration of IEnumerable fails. ASP.NET WebApi

查看:493
本文介绍了如何返回正确的状态code时的IEnumerable枚举失败。 ASP.NET的WebAPI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注:仅控制器的测试过程中出现如下问题发生。这里有精致的问题,<一个href=\"http://stackoverflow.com/questions/31451966/how-to-properly-integration-test-web-api-controller-with-ienumerable-results\">How正确集成测试的Web API控制器与IEnumerable的结果?

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?

有什么办法避免调用了ToList方法,但仍推迟执行LINQ异常的情况下,返回正确的状态code,以保持控制器尽可能简单?

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?

例如。我有这样的API端点:

E.g. I have such API endpoint:

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

以上code将始终返回成功状态code,但在了ToList执行查询任何问题的情况下,它不会成功。

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());
    }
}

为什么会这样工作的原因是清楚的,但有没有回到正确的状态code,并保持控制器简单的更聪明的方式?

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

推荐答案

您可以调试的动作,然后看看有什么异常获取引发。

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

然后你就可以轻松的try-catch此行code的,如果失败,如果你给不同的东西,然后回来500

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
}

希望它帮助。

这篇关于如何返回正确的状态code时的IEnumerable枚举失败。 ASP.NET的WebAPI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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