14

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?

2
  • Please include the class definition as well, for example, public ProductsController : ApiController { Commented Dec 20, 2012 at 12:12
  • OK. I think I got it. The class definition is: public class ProductsController : Controller Commented Dec 20, 2012 at 12:14

2 Answers 2

26

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.

Sign up to request clarification or add additional context in comments.

1 Comment

whats for .net core?
19

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.