首页 新闻 搜索 专区 学院

MVC4 web API 如何获取Post过来的json数据?一直显示null

0
悬赏园豆:50 [待解决问题]

这是提交post请求的页面

 protected void Button1_Click(object sender, EventArgs e)
    {
        string json = GetReleseUserJson();
        string str = HttpPost(json, "http://192.168.1.113/testapi/api/test");
        Response.Write(str);
    }
 
    private string HttpPost(string postDataStr, string Url)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
        request.Method = "POST";
        request.ContentType = "application/json";
        //request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
        Stream myRequestStream = request.GetRequestStream();
        StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
        myStreamWriter.Write(postDataStr);
        myStreamWriter.Close();
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Stream myResponseStream = response.GetResponseStream();
        StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
        string retString = myStreamReader.ReadToEnd();
        myStreamReader.Close();
        myResponseStream.Close();
        return retString;
    }
    //JSON字符串
    public static string GetReleseUserJson()
    {
 
      
 
        string json = "{";
        json += "\"ID\":5,";
        json += "\"Name\":\"超大厦\",";
        json += "\"Age\":55";
        json += "}";
        return json;
    }

这是web API 控制器里的

 public Test Post([FromBody]Test ttt)
        {
             
 
 
            return ttt;
        }

 


   


   



这是model里的

public class Test
    {
        public int ID { get; set; }
 
        public string Name { get; set; }
 
        public int Age { get; set; }
 
        
    }
好小豪的主页 好小豪 | 初学一级 | 园豆:80
提问于:2015-07-22 16:31
< >
分享
所有回答(3)
0

可以试试HttpClient调用。

var data = JsonConvert.SerializeObject(test);
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

var file = client.PostAsJsonAsync(url,data);

代码中test是Test的实例。

webaspx | 园豆:1987 (小虾三级) | 2015-07-23 08:33
0

可以参考我写的这篇文章中C# 请求部分

http://www.cnblogs.com/visonme/p/4637764.html

visonme | 园豆:1674 (小虾三级) | 2015-07-23 10:07
0

你POST的内容不带querystiring的.需要这样获取:

 

var s = Request.InputStream;
var b = new byte[s.Length];
s.Read(b, 0, (int) s.Length);
var postStr = Encoding.UTF8.GetString(b);

这样就可以获取到你传递的json内容了. postStr再序列化成你的对象即可

万雅虎 | 园豆:318 (菜鸟二级) | 2015-07-24 11:18
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册