阅读HttpContent中的WebAPI控制器 [英] Read HttpContent in WebApi controller
问题描述
我怎样才能阅读的内容,在MVC的WebAPI控制器动作PUT请求。
[HttpPut]
公众的Htt presponseMessage把(INT帐户ID,联系方式联系人)
{
VAR httpContent = Request.Content;
VAR asyncContent = httpContent.ReadAsStringAsync()结果。
...
我在这里得到空字符串:(
我需要做的是:找出被修改/发送初始请求(意为什么样的属性,如果联系
对象有10个属性,我要更新其中只有2,我发送和对象只有两个属性,像这样:
{ 名字:空,
名字:空,
ID:21
}
预期最终的结果是
列表<串GT; modified_properties = {名字,姓氏}
在设计中的ASP.NET Web API的主体内容被视为只进流可以一次读取。
在网页API是绑定你的模型在你的情况下,第一次读正在做的,在这之后的 Request.Content
将不会返回任何东西。
您可以从您的动作参数删除联系人
,获取内容并手动反序列化到对象(例如使用Json.NET):
[HttpPut]
公众的Htt presponseMessage把(INT帐户ID)
{
HttpContent requestContent = Request.Content;
字符串jsonContent = requestContent.ReadAsStringAsync()结果。
联系方式联系方式= JsonConvert.DeserializeObject<联络与GT;(jsonContent);
...
}
这是应该做的伎俩(假设帐户ID
是URL参数,所以它不会被视为内容读取)。
How can I read the contents on the PUT request in MVC webApi controller action.
[HttpPut]
public HttpResponseMessage Put(int accountId, Contact contact)
{
var httpContent = Request.Content;
var asyncContent = httpContent.ReadAsStringAsync().Result;
...
I get empty string here :(
What I need to do is: figure out "what properties" were modified/sent in the initial request (meaning that if the Contact
object has 10 properties, and I want to update only 2 of them, I send and object with only two properties, something like this:
{
"FirstName": null,
"LastName": null,
"id": 21
}
The expected end result is
List<string> modified_properties = {"FirstName", "LastName"}
By design the body content in ASP.NET Web API is treated as forward-only stream that can be read only once.
The first read in your case is being done when Web API is binding your model, after that the Request.Content
will not return anything.
You can remove the contact
from your action parameters, get the content and deserialize it manually into object (for example with Json.NET):
[HttpPut]
public HttpResponseMessage Put(int accountId)
{
HttpContent requestContent = Request.Content;
string jsonContent = requestContent.ReadAsStringAsync().Result;
CONTACT contact = JsonConvert.DeserializeObject<CONTACT>(jsonContent);
...
}
That should do the trick (assuming that accountId
is URL parameter so it will not be treated as content read).
这篇关于阅读HttpContent中的WebAPI控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!