如何从MVC控制器对象发布到网络API控制器? [英] How to post an object from MVC controller to Web Api controller?

查看:146
本文介绍了如何从MVC控制器对象发布到网络API控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

情景是我的MVC的观点来控制行动,并从我的行动要求是建立一个对​​象,并把它传递给外部Web API返回的数据。我M在我的行动中获取数据,并建立一个对​​象以及。你可以请直接我应该怎么传递对象外部Web API。

此外它应该是JSON,对象或XML?

我为下面给我的控制器和Web API code:

控制器动作:

 公众的ActionResult提交(的FormCollection形式)
        {
            选项​​导致=新选项();
            lead.Situation = form.GetValue(InsuranceFor)AttemptedValue。
            lead.State = form.GetValue(InsuranceState)AttemptedValue。            //在这里,我想通过对象的Web API
            返回RedirectToAction(参数);
        }

网页API方法:

 公共无效后(Lead_Options导致)
        {
            leadOptService.AddListOptions(铅);
        }


解决方案

我刚刚完成一个复杂的实施只是为了满足类似的要求。我被分配到从C#MVC控制器对象发布到外部基于REST的Web API。在未来,网络API将依然存在,但C#MVC可与的NodeJS /角应用来代替。所以我所做的就是,分配对象到TempData的一个序列化JSON格式,然后在视图所在的页面重定向到,有条件加AngularJS,并实施AngularJS发布到外部的WebAPI。在你的情况,到TempData会是这个样子:

  this.TempData [导致] =新的JavaScriptSerializer()序列化(this.Json(铅,JsonRequestBehavior.AllowGet)。数据)。

然后,在重定向视图参数,可以添加这个角度code:

  @if(this.TempData [导致]!= NULL)
{
    <脚本类型=文/ JavaScript的SRC =@ Url.Content(〜/内容/脚本/ angular.js)>< / SCRIPT>
    <脚本类型=文/ JavaScript的>
        角
       .module('应用',[])
       .controller('controllerName',['$ HTTP,$范围,apiFactory',函数($ HTTP,$范围,apiFactory){
           VAR leadRecord ='​​@ Html.Raw(this.TempData [导致])';
           VAR apiUrl ='https://开头XXXXXXXXXXXXXX';           apiFactory({
               方法:POST,
               网址:apiUrl +'/ API / apiControllerName /邮报,
               数据:'='+ leadRecord,
               标题:{内容类型:应用程序/ x-WWW的形式urlen codeD;字符集= utf-8'}
           }),然后(功能(结果){
               的console.log(结果);
           });
        }])
        .factory('apiFactory',函数($ HTTP,$ Q){
            复位功能(配置){
                变种延迟执行= $ q.defer();
                $ HTTP(配置)
                .success(功能(结果,状态,头,配置){
                    defered.resolve(结果);
                })
                返回defered.promise;
            }
        })
    < / SCRIPT>
}    < D​​IV NG-应用=应用程序级=COL-SM-12登录页的>
         < D​​IV CLASS =行NG-控制器=controllerName>          .....重定向页面内容....         < / DIV>
    < / DIV>

您的WebAPI - (假设这是C#的Web API 2.2应该是这个样子:

  [HttpPost]
    公共字符串邮报([FromBody]字符串jsonString)
    {
        尝试
        {
            IDictionary的<字符串,字符串>数据= JsonConvert.DeserializeObject<&IDictionary的LT;字符串,字符串>>(jsonString);

假设你的对象的值都是字符串....

这执行情况可能并不理想,但它的工作是肯定的。

呵呵,或者,你可以简单地角后到包含窗体控件原始视图。但对我来说,这是不是因为视图必须做出充分的帖子,从满后必须将数据模型处理的选项,然后控制器获取的一些数据从模型和会话信息结合起来,使向上的对象,然后必须被发送至Web API控制器..

Scenario is my MVC view is returning data to Controller action and from my action requirement is to build an object and pass it to an external Web API. I m getting data in my action and building an object as well. Can you please direct me how I should pass object to external Web API.

Also should it be JSON, object or xml ?

I m giving my controller and Web API code below:

Controller action:

 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 method:

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

解决方案

I just completed a complex implementation just to satisfy similar requirement. I was assigned to post object from C# MVC Controller to an external RESTful Web API. In the future, the Web API will remain, but the C# MVC may be replaced with NodeJS / Angular application. So what I did was, assign the object to a TempData in a Serialized JSON format, then in the View where the page redirects to, conditionally added AngularJS, and implement AngularJS post to the external WebAPI. In your case, the TempData would look something like this:

    this.TempData["lead"] = new JavaScriptSerializer().Serialize(this.Json(lead, JsonRequestBehavior.AllowGet).Data); 

Then, in the redirected view "Parameters", you could add this angular code:

     @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>

Your WebAPI - (Assuming it's C# Web API 2.2 should look something like this:

  [HttpPost]
    public string Post([FromBody]string jsonString)
    {
        try
        {
            IDictionary<string, string> data = JsonConvert.DeserializeObject<IDictionary<string, string>>(jsonString);

Assuming your object's values are all strings ....

This implementation may not be ideal but it does its job for sure

Oh, alternatively, you could simply add the angular POST to your original view that contains the form controls. But in my case this was not an option because the View must make a full post, the data from the full post must be processed in the model, then the controller gets some of the data from the models and combine it with session information to make up the object, which then has to be sent to a Web API controller..

这篇关于如何从MVC控制器对象发布到网络API控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆