由於我沒有找到我的問題的簡短答案,我會張貼我所做的解決方案。
由於該方法使用需要async
語句的HttpClient
方法,因此執行下面的操作時會重新調整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.
}
你你需要添加一些關於你在這裏做什麼的細節。你是指「將數據發佈到其他網站」?感覺就像你要離開控制器的單一職責 - 接受用戶交互並呈現視圖。顯然,你不能'RedirectToAction'到另一個網站,因爲它們會位於不同的應用程序域中。 –
@ChrisHardie答案根據要求更新。 –
啊,我相信你需要按摩你的模型。我認爲你的問題更像是:「我如何使用C#使用JSON發佈到Web API端點」。也許試試這個鏈接:http://blogs.msdn.com/b/wsdevsol/archive/2013/02/05/how-to-use-httpclient-to-post-json-data.aspx –