Is there any difference between CreateResponse <Content> () and CreateResponse () with Web Api?
Given the following:
[HttpGet]
[ActionName("GetContent")]
public HttpResponseMessage GetContent(int id)
{
Content content = _uow.Contents.GetById(id);
if (content == null)
{
var message = string.Format("Content with id = {0} not found", id);
return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);
}
else
{
return Request.CreateResponse(HttpStatusCode.OK, content);
}
}
and
[HttpGet]
[ActionName("GetContent")]
public HttpResponseMessage GetContent(int id)
{
try
{
Content content = _uow.Contents.GetById(id);
if (content == null)
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
}
return Request.CreateResponse<Content>(HttpStatusCode.OK, content);
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}
I saw two coding styles. One uses exceptions, and the other does not. One uses CreateResponse <> and the other uses CreateResponse (). Can anyone tell me what are the advantages / disadvantages of using them? As far as I can see, the second method looks more complete, but is it really necessary to use try / catch for something as simple as this?
The main advantage of throwing HttpResponseExceptionis when your action method returns the type of the model, and not HttpResponseMessage. For example:
public Product Get(int id)
{
Product p = _GetProduct(id);
if (p == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return p;
}
:
public HttpResponseMessage Get(int id)
{
Product p = _GetProduct(id);
if (p == null)
{
return Request.CreateResponse(HttpStatusCode.NotFound);
}
return Request.CreateResponse(HttpStatusCode.OK, p);
}
OK, .
HttpResponseException s, -API HTTP. Not Found Bad Request, , Not Found (404).
:
CreateResponse vs CreateResponse<T> HttpResponseException.
CreateResponse HTTP :
public HttpResponseMessage Get()
{
return Request.CreateResponse(HttpStatusCode.NotFound);
}
CreateResponse<T> T HTTP:
public HttpResponseMessage Get()
{
Product product = new Product();
// Serialize product in the response body
return Request.CreateResponse<Product>(HttpStatusCode.OK, product);
}
, , :
public HttpResponseMessage Get()
{
Product product = new Product();
// Serialize product in the response body
return Request.CreateResponse(HttpStatusCode.OK, product);
}
CreateErrorResponse HTTP-, HttpError. , . CreateErrorResponse :
HttpError err = new HttpError( ... )
// Serialize err in the response.
return Request.CreateResponse(HttpStatusCode.BadRequest, err);