2014-10-01 86 views
0

場景是我的MVC視圖將數據返回給Controller動作,並且從我的動作需求構建一個對象並將其傳遞給外部Web API。我在我的行動中獲取數據並構建一個對象。你能指導我如何將對象傳遞給外部Web API。如何將一個對象從MVC控制器發佈到Web Api控制器?

也應該是JSON,對象或XML?

我米給我的控制器和下面的Web API代碼:

控制器動作:

public ActionResult Submit(FormCollection form) 
     { 
      Options lead = new Options();    
      lead.Situation = form.GetValue("InsuranceFor").AttemptedValue; 
      lead.State = form.GetValue("InsuranceState").AttemptedValue; 

      //Here I want to pass object to Web API 


      return RedirectToAction("Parameters"); 
     } 

的Web API方法:

public void Post(Lead_Options lead) 
     { 
      leadOptService.AddListOptions(lead); 
     } 
+0

基本上你需要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

+0

或者使用RestSharp手動執行它,如果你感到瘋狂。 – Wjdavis5 2014-10-01 23:54:40

+0

爲什麼不直接將它傳遞給Web API端點而不是控制器?首先去控制器的原因是什麼? – 2014-10-02 00:02:51

回答

0

我剛剛完成一個複雜的實施只是爲了滿足類似需求。我被分配爲將對象從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控制器。

相關問題