两者的主要区别在于:异常用于立即停止处理并退出。例如,假设我有以下代码:
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;
}
}
如果这段代码运行,并且我传递了一个不存在的id,它将立即停止处理并返回404状态码。
如果我返回HttpResponseMessage,请求将愉快地继续其余的处理,并返回404。主要区别在于是否结束请求。
正如Darrel所说,异常在某些情况下非常有用,比如当找到顾客时我希望处理继续进行,在其他情况下则不需要。
你可能想使用类似HttpResponseMessage这样的东西来返回状态码201并设置位置头,通常在Http POST中使用。在那种情况下,我确实希望处理继续进行。这是我会用这段代码实现的内容。
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;
}
}
*注意:如果您正在使用beta版本,则需要创建新的HttpResponseMessage。但我正在使用较新的版本,所以需要使用Request的CreateResponse扩展方法。
以上代码创建了一个响应,将状态码设置为201,将客户端传递进去,然后设置位置头。
然后返回该响应并继续处理请求。
希望这能帮到您。