zoukankan      html  css  js  c++  java
  • C# .NET MVC 接收 JSON ,POST,WCF 无缝隙切换

    用来与HTTP 模式的WCF 无缝隙切换。

    服务端是MVC。

    在Home/About 上面加 [HttpPost]。读取Request.InputStream 中所有内容。然后返回JSON给客户端:return Json(c1);。

     
     [HttpPost]
            public ActionResult About()
            {
                
                string dfCharSet = "utf-8";
                if (Request.QueryString["charset"] != null)
                    dfCharSet = Request.QueryString["charset"];
                Encoding ec = Encoding.GetEncoding(dfCharSet);
                string inStr = string.Empty;
                using (StreamReader sr = new StreamReader(Request.InputStream, ec))
                {
                    inStr = sr.ReadToEnd();
                }
                Models.Class1 c1 = new Models.Class1();
                c1.name = "服务器";
                c1.inStr = inStr;
            Response.ContentEncoding = ec;
    return Json(c1); }

    客户端。POST JSON 到服务端,接收服务端返回的JSON。建议用HttpWebRueqest.

     try
                {
                    Class1 c1 = new Class1();
                    c1.name = "客户端";
                    c1.inStr = "";
    
                    string input = JsonConvert.SerializeObject(c1);
    
                    byte[] bts = Encoding.UTF8.GetBytes(input);
                    byte[] btRst;
    
                    using (WebClient wc = new WebClient())
                    {
                        string url = "http://localhost:52844/Home/About";
    
                        wc.Encoding = Encoding.UTF8;
                        btRst = wc.UploadData(url, "post", bts);
                    }
                    string rst = Encoding.UTF8.GetString(btRst);
                    MessageBox.Show(rst);
                }
                catch (Exception ex)
                { MessageBox.Show(ex.Message); }

    -

  • 相关阅读:
    PAT 05-树7 File Transfer
    PAT 05-树6 Path in a Heap
    PAT 10-2 删除字符串中的子串
    PAT 10-1 在字符串中查找指定字符
    PAT 10-0 说反话
    PAT 08-2 求矩阵的局部最大值
    PAT 07-3 求素数
    PAT 07-2 A+B和C
    PAT 07-0 写出这个数
    PAT 06-3 单词长度
  • 原文地址:https://www.cnblogs.com/runliuv/p/5927781.html
Copyright © 2011-2022 走看看