ASP.NET MVC,抛出HttpException vs返回HttpStatusCodeResult吗? [英] ASP.NET MVC, throw HttpException vs return HttpStatusCodeResult?

查看:189
本文介绍了ASP.NET MVC,抛出HttpException vs返回HttpStatusCodeResult吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发RESTful服务,我想为所有不受支持的URL返回400.

I am developing a RESTful service and I want to return 400 for all unsupported URLs.

我的问题是我何时应该选择方法1而不是方法2,反之亦然.

//method 1
public ActionResult Index()
{
    //The url is unsupported
    throw new HttpException(400, "Bad Request");
}

这似乎更好?

//method 2
public ActionResult Index()
{
    //The url is unsupported
    return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Bad Request");
}

推荐答案

处于 DevOps 在团队中,我们全都处于思维定势中,在某个事物上投入更多的硬件以获得更好的结果永远是一个好理由.因此,我故意忽略了触发.NET异常的微小代价.

Being in a DevOps team, we are all in the mind-set where throwing more hardware at something to get a slightly better result is always a good cause. So I'm intentionally ignoring the micro-cost of firing a .NET exception.

如果您使用的遥测框架如 ApplicationInsights ,则只需返回状态码,您只会得到失败的请求".它没有提供任何有用的信息,使您无法编译或获取有关失败请求的原因"的任何信息.

If you're leveraging a telemetry framework like ApplicationInsights then just returning the status code gives you nothing more than a "failed request". It doesn't give you any useful information that allows you to either compile or get any information on the "why" of the failed request.

遥测平台期望并希望您抛出异常,因为错误遥测通常围绕.NET异常,因此,如果不抛出异常,则会给操作造成问题.

Telemetry platforms expect and want you to throw, because error telemetry is usually around .NET exceptions, so if you're not throwing you're creating a problem for operations.

我实际上是在这里着陆的,因为我正在编写一个罗斯林分析器和CodeFix用于一个人们喜欢写try{} catch { return BadRequest("put_the_reason_here"); }的项目,DevOps或Dev团队都认为ApplicationInsights中的系统遥测没有任何用处.

I actually landed here, because I'm in the process of writing a Roslyn analyser and CodeFix for a project where folks love to write try{} catch { return BadRequest("put_the_reason_here"); } and neither DevOps or the Dev teams see nothing useful in the system telemetry in ApplicationInsights.

这篇关于ASP.NET MVC,抛出HttpException vs返回HttpStatusCodeResult吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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