如何将Json从Win Forms传递给MVC Controller

时间:2014-09-17 08:38:42

标签: c# asp.net-mvc json winforms

我在下面给出了MVC控制器:

public ActionResult ReceiveJson(string json)
{
    //--

    return Content(json, "application/json");

}

我创建了Windows窗体应用程序。在应用程序中,我想将Json传递给我的MVC控制器。

我用:

string json = new JavaScriptSerializer().Serialize(myObject);

    using (var client = new CookieAwareWebClient())
    {
        var values = new NameValueCollection
            {
                { "username", login },
                { "password", haslo },
            };

        client.UploadValues("http://localhost/xxxxx/Login", values);

        string link = "http://localhost/xxx/ReceiveJson";

        client.Headers.Add("Content-Type", "application/json");
        var response = client.UploadString(new Uri (link), "POST", json);
    }

此代码不起作用。在ReceiveJson控制器中,我收到了null。

http://s22.postimg.org/9vxu2no9t/json.jpg

你能告诉我如何将Json从Win Forms传递给MVC控制器吗?

谢谢; - )

5 个答案:

答案 0 :(得分:2)

以下是工作代码示例:

var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost/CONTROLLER_NAME/ReceiveJson");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "GET";

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
    string json = new JavaScriptSerializer().Serialize(myObject);

    streamWriter.Write(json);
    streamWriter.Flush();
    streamWriter.Close();

    // If you need to read response
    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
        var result = streamReader.ReadToEnd();
    }
}

答案 1 :(得分:0)

你在发送之前检查了你的json值吗? 你有没有尝试上传字符串而不添加额外的标题?在您的操作中,您接收字符串而不是对象。 Here就是一个很好的例子。

答案 2 :(得分:0)

看起来你违反了一些MVC惯例。

  • 首先,您应该在请求正文中发布您的值而不是JSON。它看起来像这样

    using(var content = new MultipartFormDataContent())
    {
        content.Add(new StringContent(firstPropertyName), "firstValue");
        content.Add(new StringContent(secondPropertyName), "secondValue");
    
        client.PostAsync("https://mydomain.com/xxx/ReceiveJson", content);
    }
    
  • 其次,您应该使用[HttpPost]属性

  • 标记您的操作
  • 第三,你应该尝试接收你的viewModel而不是字符串。它将简化您在服务器上的代码

我相信这会有所帮助。

答案 3 :(得分:0)

这是一个很好的工作版本:

public ActionResult NamiaryWyZapis()
{                
                Stream jsonDane = Request.InputStream;
                jsonDane.Seek(0, System.IO.SeekOrigin.Begin);

                string json = new StreamReader(jsonDane).ReadToEnd();
//--
}

答案 4 :(得分:0)

答案:通过POST。

您需要将对象(在本例中为Persons)序列化为json,并使用类似这样的方法发布帖子。 (必须可以从两个应用程序访问人员模型)

 public async bool SendRequestAsync(string requestUrl, object data) 
    {
        string json = JsonConvert.SerializeObject(obj, Formatting.Indented,
                                 new JsonSerializerSettings
                                 {
                                     ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                                 });

        try
        {
            HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;

            if (request != null)
            {
                request.Accept = "application/json";
                request.ContentType = "application/json";
                request.Method = "POST";

                using (var stream = new StreamWriter(await request.GetRequestStreamAsync()))
                {
                    stream.Write(json);
                }

                using (HttpWebResponse response = await request.GetResponseAsync() as HttpWebResponse)
                {
                    if (response != null && response.StatusCode != HttpStatusCode.OK)
                        throw new Exception(String.Format(
                            "Server error (HTTP {0}: {1}).",
                            response.StatusCode,
                            response.StatusDescription));

                    if (response != null)
                    {
                        Stream responseStream = response.GetResponseStream();
                        //return true or false depending on the ok
                        return GetResponseModel(responseStream);
                    }
                }
            }
        }
        catch (WebException ex)
        {
            var response = ex.Response;
            Stream respStream = response.GetResponseStream();
            //return true or false depending on the ok
            return GetResponseModel(respStream);

        }
        catch (Exception e)
        {
            return false;
        }

        return false;
    }

如果您的POST成功,GetResponseModel方法将返回您要从Web读取的模型。然后在您的WinForms中,您可以根据需要注册该成功。

控制器方法看起来像这个

[HttpPost]
public ActionResult JsonMethod(Person p)
{
    if(p != null)
      return Json(true);
    else return Json(false);
}

GetResponse的正文可能就像这个

public static T GetResponseModel<T>(Stream respStream) where T : class
        {
            if (respStream != null)
            {
                var respStreamReader = new StreamReader(respStream);
                Task<string> rspObj = respStreamReader.ReadToEndAsync();
                rspObj.Wait();
                T jsonResponse = JsonConvert.DeserializeObject<T>(rspObj.Result);

                return jsonResponse;
            }

            return default(T);
        }