C# HttpResponseMessage 和 HttpResponseException 有什么区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10660721/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the difference between HttpResponseMessage and HttpResponseException
提问by cuongle
I tried to understand both and write sample code:
我试图理解两者并编写示例代码:
public HttpResponseMessage Get()
{
var response = ControllerContext.Request
.CreateResponse(HttpStatusCode.BadRequest, "abc");
throw new HttpResponseException(response);
}
And:
和:
public HttpResponseMessage Get()
{
return ControllerContext.Request
.CreateResponse(HttpStatusCode.BadRequest, "abc");
}
From Fiddle, I really didn't see any differences between them, so what is the purpose of using HttpResponseException?
从 Fiddle 来看,我真的没有看到它们之间的任何区别,那么使用 的目的是HttpResponseException什么?
采纳答案by Glenn Block
The main difference between the two is this. The exception is useful to immediately stop processing and exit. For example assume I have the following code
两者的主要区别在于这一点。该异常对于立即停止处理并退出很有用。例如假设我有以下代码
public class CustomerController : ApiController {
private ICustomerContext repo;
public CustomerController(ICustomerContext repo) {
this.repo = repo;
}
public Customer Get(int id) {
var customer = repo.Customers.SingleOrDefault(c=>c.CustomerID == id);
if (customer == null) {
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
}
return customer;
}
}
If this code runs and I pass an id that is not present, it will immediately stop processing and return a status code of 404.
如果此代码运行并且我传递了一个不存在的 id,它将立即停止处理并返回状态代码 404。
If instead I return HttpResponseMessage, the request will happily continue the rest of its processing and return a 404. The main difference being end the request or not.
相反,如果我返回 HttpResponseMessage,该请求将继续其处理的其余部分并返回 404。主要区别在于是否结束请求。
As Darrel said the exception is useful in cases where in some cases I want processing to continue (as in when customer is found) and in others I don't.
正如 Darrel 所说,在某些情况下我希望处理继续(例如找到客户时)而在其他情况下我不希望处理的情况下,异常很有用。
The place where you might want to use something like HttpResponseMessage is in an Http POST to return a status code of 201 and set the location header. In that case I do want processing to continue. That would would do with this code.*
您可能想要使用 HttpResponseMessage 之类的地方是在 Http POST 中返回状态代码 201 并设置位置标头。在这种情况下,我确实希望继续处理。用这个代码就可以了。*
public class CustomerController : ApiController {
private ICustomerContext repo;
public CustomerController(ICustomerContext repo) {
this.repo = repo;
}
public HttpResponseMessage Post(Customer customer) {
repo.Add(customer);
repo.SaveChanges();
var response = Request.CreateResponse(HttpStatusCode.Created, customer);
response.Headers.Location = new Uri(Request.RequestUri, string.format("customer/{0}", customer.id));
return response;
}
}
*note: If you are using the beta bits you would create a new HttpResponseMessage. I am using the later bits however which require you to use the CreateResponse extension method off of the Request.
*注意:如果您使用的是 beta 位,您将创建一个新的 HttpResponseMessage。但是,我正在使用后面的位,这要求您使用请求之外的 CreateResponse 扩展方法。
Above, I am creating a response which sets the status code to 201, passes in the customer, and then sets the location header.
上面,我正在创建一个响应,它将状态代码设置为 201,传入客户,然后设置位置标头。
The response is then returned and the request continues processing.
然后返回响应并继续处理请求。
Hope this helps
希望这可以帮助
回答by labilbe
HttpResponseExceptionderives from Exceptionand embeds HttpResponseMessage.
Since it derives from Exceptionit can be useful in try-catchscenarios.
HttpResponseException源自Exception并嵌入HttpResponseMessage. 因为它派生自Exception它在try-catch场景中很有用。
Default status code returned by HttpResponseExceptionis HttpStatusCode.InternalServerError.
返回的默认状态代码HttpResponseException是HttpStatusCode.InternalServerError。
回答by Darrel Miller
HttpResponseException is useful when your Controller Action signature looks like
当您的控制器操作签名看起来像这样时,HttpResponseException 很有用
Foo Get(int id)
In this case, you cannot easily return status code like 400.
在这种情况下,您不能轻易返回 400 之类的状态代码。
Be aware that HttpResponseMessage<T>is going away in the next release of Web API.
请注意,HttpResponseMessage<T>在 Web API 的下一个版本中,这将消失。
回答by Brian Vallelunga
Assuming you want to unit test the responses, doesn't it make sense to always return an HttpResponseMessage? I don't particularly like the idea of returning a straight type from an ApiController since it doesn't follow typical development patterns.
假设您想对响应进行单元测试,那么总是返回一个 HttpResponseMessage 难道没有意义吗?我不太喜欢从 ApiController 返回直接类型的想法,因为它不遵循典型的开发模式。
In a non-Web API class that fetched a Customer, you'd likely return null, with your calling code checking for a null response:
在获取 Customer 的非 Web API 类中,您可能会返回 null,您的调用代码会检查 null 响应:
public Customer GetCustomer(int id)
{
return db.Customers.Find(id);
}
But in Web API, you're not going to return null, you have to return something, even if that something is created after you throw an HttpResponseException. In that case, to ease testing, why not just always return an HttpResponseMessage, and make that your signature?
但是在 Web API 中,您不会返回 null,您必须返回某些内容,即使该内容是在您抛出 HttpResponseException 之后创建的。在这种情况下,为了简化测试,为什么不总是返回一个 HttpResponseMessage,并将其作为您的签名?
public HttpResponseMessage GetCustomer(int id)
{
var customer = db.Customers.Find(id);
if (customer == null)
{
return Request.CreateResponse(HttpStatusCode.NotFound);
}
return Request.CreateResponse(HttpStatusCode.OK, customer);
}
回答by Mikee
As the original questions states, there is no real difference in the returned Response.
正如原始问题所述,返回的 Response 没有真正的区别。
The real purpose of HttpResponseException is to allow sub methods to create and 'throw' their own HttpResponseMessages that flow back to the up the call stack and are returned to the client.
HttpResponseException 的真正目的是允许子方法创建和“抛出”它们自己的 HttpResponseMessages,这些 HttpResponseMessages 流回到调用堆栈的上方并返回给客户端。
public class CustomerController : ApiController {
private ICustomerContext repo;
public CustomerController(ICustomerContext repo) {
this.repo = repo;
}
public HttpResponseMessage Get(int id) {
Customer customer = getCustomer(id);
return Request.CreateResponse(customer);
}
private Customer getCustomer(int id){
.....do some work
.....we have a problem so throw exception
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest, "Id out of range");
return repo.Customers.SingleOrDefault(c=>c.CustomerID == id)
}
Forgive any mistakes, code written on the fly. The thrown HttpResponseException bubbles up thru the actions call stack, does not get caught by normal Exception handlers and returns its HttpResponseMessage like the action method itself would have.
原谅任何错误,即时编写的代码。抛出的 HttpResponseException 通过操作调用堆栈向上冒泡,不会被普通异常处理程序捕获并像操作方法本身那样返回其 HttpResponseMessage。

