我有两个站点:其中一个控制另一个通过Web发送一些命令。其思想是:控制器站点的操作向另一个站点发送一个命令,获取响应并执行一些业务规则,而不重定向到另一个站点。
我有大量的例子来解释如何通过jQuery实现这一点,但是我想让控制器将数据发布到另一个站点,而不是视图。
我在这个答案中找到了一种方法:How to use System.Net.HttpClient to post a complex type?,但是我想要一个JSON方法的答案。
有人能用JSON发布一个简单的例子来展示如何做到这一点吗?
发布于 2013-11-27 18:41:39
由于我没有找到我的问题的简短答案,我将张贴我已经做好的解决方案。
由于该方法使用了一个需要HttpClient
语句的async
方法,因此实现了对Task<ActionResult>
的重新配置。另一个修改是在上下文中保存对象。
而不是使用:
context.SaveChanges();
你必须使用:
await context.SaveChangesAsync();
下面的代码实现了来自ASP.NET MVC4控制器的一个操作:
[HttpPost]
public async Task<ActionResult> Create(MyModel model)
{
if (ModelState.IsValid)
{
// Logic to save the model.
// I usually reload saved data using something kind of the statement below:
var inserted = context.MyModels
.AsNoTracking()
.Where(m => m.SomeCondition == someVariable)
.SingleOrDefault();
// Send Command.
// APIMyModel is a simple class with public properties.
var apiModel = new APIMyModel();
apiModel.AProperty = inserted.AProperty;
apiModel.AnotherProperty = inserted.AnotherProperty;
DataContractJsonSerializer jsonSer = new DataContractJsonSerializer(typeof(APIMyModel));
// use the serializer to write the object to a MemoryStream
MemoryStream ms = new MemoryStream();
jsonSer.WriteObject(ms, apiModel);
ms.Position = 0;
//use a Stream reader to construct the StringContent (Json)
StreamReader sr = new StreamReader(ms);
// Note if the JSON is simple enough you could ignore the 5 lines above that do the serialization and construct it yourself
// then pass it as the first argument to the StringContent constructor
StringContent theContent = new StringContent(sr.ReadToEnd(), System.Text.Encoding.UTF8, "application/json");
HttpClient aClient = new HttpClient();
Uri theUri = new Uri("http://yoursite/api/TheAPIAction");
HttpResponseMessage aResponse = await aClient.PostAsync(theUri, theContent);
if (aResponse.IsSuccessStatusCode)
{
// Success Logic. Yay!
}
else
{
// show the response status code
String failureMsg = "HTTP Status: " + aResponse.StatusCode.ToString() + " - Reason: " + aResponse.ReasonPhrase;
}
return RedirectToAction("Index");
}
// if Model is not valid, you can put your logic to reload ViewBag properties here.
}
https://stackoverflow.com/questions/20181824
复制相似问题