簡體   English   中英

如何將Json從Win Forms傳遞到MVC Controller

[英]How I can pass Json from Win Forms to MVC Controller

我有下面給出的MVC控制器:

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

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

}

我創建了Windows窗體應用程序。 在應用程序中,我想將Json傳遞給我的MVC Controller。

我用:

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 Controller中,我收到了null。

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

您能告訴我如何將Json從Win Forms傳遞到MVC Controller嗎?

謝謝 ;-)

這是工作代碼示例:

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

發送之前檢查過json值了嗎? 您是否嘗試過在不添加額外標題的情況下上傳字符串? 在您的操作中,您收到的不是字符串對象。 是一個很好的例子。

您似乎違反了某些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而不是字符串。 它將簡化服務器上​​的代碼

我相信這會有所幫助。

這是一個很好的工作版本:

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

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

解答:通過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);
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM