CreateResponse方法在asp.net的Web API [英] CreateResponse method in asp.net Web API

查看:430
本文介绍了CreateResponse方法在asp.net的Web API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

调用这个方法:

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?

推荐答案

项目的运行时类型可能不是的产品。你应该能够做到这一点:

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);

即使项目产品,通用&LT的实例;产品&GT; 的说法是多余的,没有必要的。如果你使用ReSharper的,它会告诉你,(通用)类型的参数规格是多余的。

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".

更新

请问你类从控制器延长 ApiController ?其误差应'System.Net.Http.Htt prequestMessage'不包含... ,而不是系统的定义。 Web.Htt prequestBase'不包含......一个定义

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控制器应该从 ApiController 延长,而不是控制器。在一个MVC控制器, this.Request System.Web.Htt prequestBase 的一个实例。在控制器的WebAPI, this.Request System.Net.Http.Htt prequestMessage 的一个实例

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.

这篇关于CreateResponse方法在asp.net的Web API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆