从MVC POST操作方法调用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
    }

不知道如何进行,任何帮助都表示感谢。

您不应该使用POST重定向,重定向几乎总是使用GET,但无论如何您都不想重定向到API:浏览器将如何处理响应?

您必须从MVC控制器执行POST并返回数据。

类似这样的东西:

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

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

在控制器中使用

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

最新更新