如何将一个对象从MVC控制器发布到Web Api控制器?

问题描述:

场景是我的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

我刚刚完成一个复杂的实施只是为了满足类似需求。我被分配为将对象从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控制器。