澄清:POST请求位于同一项目中的不同网站或不同控制器之间。
我想将Json数据发布到另一个操作方法。我使用Newtonsoft进行json序列化,事实是在JsonMethod中,字段Name带有null。我错过了什么吗?
我的模特:
class Person
{
[JsonProperty("name")]
public string Name{get;set;}
}
发布json的动作方法:
public ActionResult Method1()
{
Person p = new Person(){Name = "Test"}
string urlToRedirect = "..urlRoute../JsonMethod";
var res = SendRequest(urlToRedirect, p);
//...do anything with res
}
接收模型的方法
[HttpPost]
public ActionResult JsonMethod(Person p)
{
if(p.Name == "Test")
return Json("ok");
else return Json("bad");
}
发送请求的方法
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;
}
答案 0 :(得分:0)
我的错误是人的“名字”属性属性,它必须是大写字母“姓名”。这就是为什么它是空的。
[JsonProperty( “名称”)]