简体   繁体   中英

How I can pass Json from Win Forms to MVC Controller

I have MVC Controller given below:

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

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

}

I created Windows Forms Application. In the application I want to pass Json to my MVC Controller.

I use:

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

This code doesn't work. In ReceiveJson Controller I received null.

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

Can you tell me how I can pass Json from Win Forms to MVC Controller?

Thanks ;-)

Here is working code example:

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

have you checked your json value before send it? Have you tried to uploadstring without adding extra header? In your action you receave string not an object. Here is a good example.

Looks like you violated some MVC conventions.

  • First you should post your values in request body not in JSON. It will look like this

     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); } 
  • Second you should mark your Action with [HttpPost] attribute

  • Third you should try to receive your viewModel not a string. It will simplify your code on the server

I believe it will help.

It's a good working version:

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

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

ANSWER: Via POST.

You need to serialize your object(on this case Persons) to json and make a post with a method like this one. (Person model must be accessible from both applications)

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

The GetResponseModel method returns the model that you want to read from the web if your POST was success. Then in your WinForms you can register that success if you want.

The controller method will look like this one

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

The body of your GetResponse could be like this one

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM