【问题标题】:Call to Web API from MVC POST action method and receive a result从 MVC POST 操作方法调用 Web API 并接收结果
【发布时间】:2015-02-07 13:21:57
【问题描述】:

我正在尝试从 MVC POST 操作方法调用 Web API 并接收结果但不确定如何,例如:

    [HttpPost]
    public ActionResult Submit(Model m)
    {
        // Get the posted form values and add to list using model binding
        IList<string> MyList = new List<string> { m.Value1,
                m.Value2, m.Value3, m.Value4};

        return Redirect???? // Redirct to web APi POST

        // Assume this would be a GET?
        return Redirect("http://localhost:41174/api/values")
    }

我希望将上面的 MyList 发送到 Web Api 进行处理,然后它将结果(int)发送回原始控制器:

// POST api/values
    public int Post([FromBody]List<string> value)
    {
        // Process MyList

        // Return int back to original MVC conroller
    }

不知道如何继续,感谢任何帮助。

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-4 asp.net-web-api


    【解决方案1】:

    您不应该使用 POST 重定向 a redirect almost always uses GET,但无论如何您也不想重定向到 API:浏览器将如何处理响应?

    您必须执行POST from your MVC controller and return the data

    类似这样的:

    [HttpPost]
    public ActionResult Submit(Model m)
    {
        // Get the posted form values and add to list using model binding
        IList<string> postData  = new List<string> { m.Value1, m.Value2, m.Value3, m.Value4 };
    
        using (var client = new HttpClient())
        {
            // Assuming the API is in the same web application. 
            string baseUrl = HttpContext.Current
                                        .Request
                                        .Url
                                        .GetComponents(UriComponents.SchemeAndServer, UriFormat.SafeUnescaped);
            client.BaseAddress = new Uri(baseUrl);
            int result = client.PostAsync("/api/values", 
                                          postData, 
                                          new JsonMediaTypeFormatter())
                                .Result
                                .Content
                                .ReadAsAsync<int>()
                                .Result;
    
            // add to viewmodel
            var model = new ViewModel
            {
                intValue = result
            };
    
            return View(model);
        }           
    }
    

    【讨论】:

    • 不完全正确,HTTP 307 保持动词不变。但与我承认的问题或答案并不真正相关!
    • @Dean 正确,也在我链接到的链接中进行了解释。已修复,谢谢。
    • 当我尝试创建 baseUrl 时,我得到了 'System.Web.HttpContextBase' does not contain a definition for 'Current' 和 Im using System.Web;
    • @Juan 尝试将该错误放在您最喜欢的网络搜索引擎中。
    • 好的,知道了。我确实搜索了所需的命名空间,我认为我的 VS 坏了或其他什么。下次应该做更深入的搜索。
    【解决方案2】:

    您的 Web API 控制器本身不应该做太多事情。在具有适当关注点分离的应用程序中,您的处理应该在其他地方完成。例如:

    这可能在您的域模型中。

    public class StringUtilities
    {
        //Just a representative method of one way of processing the strings
        public int CountSomeStrings(IEnumerable<string> strings)
        {
            return strings.Count();
        }
    }
    

    Web API 的一部分

    // POST api/values
    public int Post([FromBody]List<string> value)
    {
        return StringUtilities.CountSomeStrings(value);
    }
    

    然后在您的 MVC 控制器中调用,无需调用 Web API。直接调用它调用的方法即可。

    [HttpPost]
    public ActionResult Submit(Model m)
    {
        // Get the posted form values and add to list using model binding
        IList<string> MyList = new List<string> { m.Value1,
                m.Value2, m.Value3, m.Value4};
    
        int NumStrings = StringUtilities.CountSomeStrings(MyList);
        ViewBag["NumStrings"] = NumStrings;
        return View();
    }
    

    【讨论】:

      【解决方案3】:

      在控制器中使用它

      public async Task<ActionResult> EmployeeRegister(CreateEmployee model)
      {
          HttpClient client = new HttpClient();
          client.BaseAddress = new Uri("http://localhost:8082/");
          client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
          client.DefaultRequestHeaders.Accept.Clear();
      
          HttpResponseMessage response = await client.PostAsJsonAsync("api/CreateEmployee/PostEmployee", model);
      
          if (response.IsSuccessStatusCode == true)
          {
              return View();
           }
      
          return View();
      }
      

      【讨论】:

        猜你喜欢
        • 2014-10-14
        • 1970-01-01
        • 1970-01-01
        • 2020-04-11
        • 1970-01-01
        • 2019-07-02
        • 2013-09-09
        • 2018-09-21
        • 2013-01-07
        相关资源
        最近更新 更多