我正在从控制台应用程序调用MVC3控制器操作(JSONRESULT)。为了打电话,我正在使用system.net.http.httpclient和postasjsonasync方法。
在AsjsonAsync方法中,我正在传递一个小的Poco实例。
这一切都很好。
我的问题是我无法在呼叫MVC3控制器操作的poco实例。 有人可以告诉我如何做吗?
这是代码:
在控制台应用程序中调用代码:
var client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:50285/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var user = new HashedUser { UserName = "userName", PasswordHash = "abcdef".GetHashCode() };
var response = client.PostAsJsonAsync("app/test", user).Result;
var txt = response.Content.ReadAsAsync<string>().Result;
在MVC3项目中接收代码
public class AppController : Controller
{
public JsonResult Test(HashedUser json)
{
// Problem: json is always a new instance
// of HashedUser and not the one passed in
// from the call to this controller action.
return Json("qqq ppp 777 888" + json.UserName);
}
}
public class HashedUser
{
public string UserName { get; set; }
public int PasswordHash { get; set; }
}
您应该序列化并将poco发送为JSON对象。使用newtonsoft.json做到这一点。这是一些样本:
http://james.newtonking.com/pages/json-net.aspxhttp://www.west-wind.com/weblog/posts/2012/aug/30/using-jsonnet-for-dynamic-json-parsing