如何将Json从Win Forms传递到MVC控制器
本文关键字:MVC 控制器 Forms Win Json | 更新日期: 2023-09-27 18:22:19
我有下面给出的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控制器吗?
谢谢;-)
下面是工作代码示例:
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]属性标记您的Action
- 第三,您应该尝试接收您的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);
}