阅读HttpContent MVC中的WebAPI控制器 [英] Read HttpContent in MVC webApi controller

查看:308
本文介绍了阅读HttpContent MVC中的WebAPI控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能阅读的内容,在MVC的WebAPI控制器动作PUT请求。

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 :(

我需要做的是找出进行了修改,什么样的属性/在初始请求发送(也就是说,如果接触的对象有10个属性,我想更新其中只有2,我发送和只对象两个属性,水木清华这样的:

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, smth like this:

{

    "FirstName": null,
    "LastName": null,

    "id": 21
}

预计最终的结果是列表<串GT; modified_properties = {名字,姓氏}

推荐答案

在设计中的ASP.NET Web API的主体内容被视为只进流可以一次读取。

By design the body content in ASP.NET Web API is treated as forward-only stream that can be read only once.

在网页API是绑定你的模型在你的情况下,第一次读正在做的,在这之后的 Request.Content 将不会返回任何东西。

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.

您可以从您的动作参数删除联系人,获取内容并手动反序列化到对象(例如使用Json.NET):

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

这是应该做的伎俩(假设帐户ID 是URL参数,所以它不会被视为内容读取)。

That should do the trick (assuming that accountId is URL parameter so it will not be treated as content read).

这篇关于阅读HttpContent MVC中的WebAPI控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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