Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CreateResponse method in asp.net Web API

calling this method:

public HttpResponseMessage PostProduct(Product item)
{
    item = repository.Add(item);
    var response = this.Request.CreateResponse<Product>CreateResponse(HttpStatusCode.Created, item);

    string uri = Url.RouteUrl("DefaultApi", new { id = item.Id });
    response.Headers.Location = new Uri(uri);
    return response;
}

Is causing a compile-time error:

'System.Web.HttpRequestBase' does not contain a definition for 'CreateResponse' and the
            best extension method overload 'System.Net.Http.HttpRequestMessageExtensions.CreateResponse<T>
(System.Net.Http.HttpRequestMessage, System.Net.HttpStatusCode, T)' has some invalid arguments.

What am I missing here?

like image 244
ronen Avatar asked Dec 20 '12 11:12

ronen


People also ask

How do I return a message in Web API?

Depending on which of these is returned, Web API uses a different mechanism to create the HTTP response. Convert directly to an HTTP response message. Call ExecuteAsync to create an HttpResponseMessage, then convert to an HTTP response message. Write the serialized return value into the response body; return 200 (OK).

What are the methods that create HttpResponseMessage with request?

CreateResponse<T>(HttpRequestMessage, HttpStatusCode, T, MediaTypeFormatter) Helper method that creates a HttpResponseMessage with an System.

What is the use of HttpResponseMessage?

A HttpResponseMessage allows us to work with the HTTP protocol (for example, with the headers property) and unifies our return type. In simple words an HttpResponseMessage is a way of returning a message/data from your action.


2 Answers

The runtime type of item is probably not an instance of Product. You should be able to do this:

var response = Request.CreateResponse(HttpStatusCode.Created, item);

Even if item was an instance of Product, the generic <Product> argument is redundant and not necessary. If you used ReSharper, it would tell you that the "(Generic) Type argument specification is redundant".

Update

Does your class extend from Controller or ApiController? The error should be 'System.Net.Http.HttpRequestMessage' does not contain a definition for..., not 'System.Web.HttpRequestBase' does not contain a definition for....

WebApi controllers should extend from ApiController, not Controller. In an MVC controller, this.Request points to an instance of System.Web.HttpRequestBase. In a WebAPI controller, this.Request points to an instance of System.Net.Http.HttpRequestMessage.

like image 189
danludwig Avatar answered Sep 18 '22 18:09

danludwig


CreateResponse is an extension method defined in System.Net.Http namespace. Make sure to add a reference to System.Net.Http and System.Net.Http.Formatting in your project and add a correct using directive:

C#:
using System.Net.Http;

VB:
Import System.Net.Http

like image 35
Karanvir Kang Avatar answered Sep 17 '22 18:09

Karanvir Kang