両者の主な違いはこれです。例外は、処理をすぐに停止して終了するのに役立ちます。たとえば、次のコードがあるとします
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 を返します。主な違いは、リクエストを終了するかどうかです。
ダレルが言ったように、例外は、処理を続行したい場合 (顧客が見つかった場合など) とそうでない場合に役立ちます。
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;
}
}
*注意: ベータ版を使用している場合は、新しい HttpResponseMessage を作成します。私は後のビットを使用していますが、リクエストから CreateResponse 拡張メソッドを使用する必要があります。
上記では、ステータス コードを 201 に設定し、顧客を渡し、ロケーション ヘッダーを設定する応答を作成しています。
その後、応答が返され、要求の処理が続行されます。
お役に立てれば