从MVC POST操作方法调用Web API并接收结果

时间:2015-02-07 13:21:57

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

我试图从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
    }

不知道如何继续,任何帮助表示赞赏。

3 个答案:

答案 0 :(得分:8)

您不应该使用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);
    }           
}

答案 1 :(得分:4)

您的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();
}

答案 2 :(得分:0)

在Controller中使用

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();
}