我剛剛完成一個複雜的實施只是爲了滿足類似需求。我被分配爲將對象從C#MVC控制器發佈到外部RESTful Web API。將來,Web API將保留,但C#MVC可能會被NodeJS/Angular應用程序所取代。所以我做的是,將對象以序列化的JSON格式分配給TempData,然後在頁面重定向到的View中,有條件地添加AngularJS,並將AngularJS post實現到外部WebAPI。在你的情況下,TempData的將是這個樣子:
this.TempData["lead"] = new JavaScriptSerializer().Serialize(this.Json(lead, JsonRequestBehavior.AllowGet).Data);
然後,在重定向視圖「參數」,你可以添加這個角度代碼:
@if (this.TempData["lead"] != null)
{
<script type="text/javascript" src="@Url.Content("~/Contents/Scripts/angular.js")"></script>
<script type="text/javascript">
angular
.module('app', [])
.controller('controllerName', ['$http', '$scope', 'apiFactory', function ($http, $scope, apiFactory) {
var leadRecord = '@Html.Raw(this.TempData["lead"])';
var apiUrl = 'https://xxxxxxxxxxxxxx';
apiFactory({
method: 'POST',
url: apiUrl + '/api/apiControllerName/Post',
data: '=' + leadRecord,
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8' }
}).then(function (result) {
console.log(result);
});
}])
.factory('apiFactory', function ($http, $q) {
return function (config) {
var defered = $q.defer();
$http(config)
.success(function (result, status, headers, config) {
defered.resolve(result);
})
return defered.promise;
}
})
</script>
}
<div ng-app="app" class="col-sm-12 sign-in-page">
<div class="row" ng-controller="controllerName">
..... contents of redirected page ....
</div>
</div>
你的WebAPI - (假設這是C#網絡API 2.2應該是這個樣子:
[HttpPost]
public string Post([FromBody]string jsonString)
{
try
{
IDictionary<string, string> data = JsonConvert.DeserializeObject<IDictionary<string, string>>(jsonString);
假設你的對象的值都是字符串....
這個實現可能並不理想,但它的確可以工作
噢,或者,您可以簡單地將角度POST添加到包含表單控件的原始視圖。但在我的情況下,這不是一種選擇,因爲View必須發佈完整的帖子,必須在模型中處理完整帖子中的數據,然後控制器從模型中獲取一些數據並將其與會話信息結合起來然後必須發送到Web API控制器。
基本上你需要ac#Web API客戶端。 ...我會看到這個http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client – 2014-10-01 23:51:28
或者使用RestSharp手動執行它,如果你感到瘋狂。 – Wjdavis5 2014-10-01 23:54:40
爲什麼不直接將它傳遞給Web API端點而不是控制器?首先去控制器的原因是什麼? – 2014-10-02 00:02:51