4

I am trying to call to a Web API from MVC POST action method and receive a result but not sure how, for example:

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

I wish to send the above MyList to the Web Api to be processed, then it will send a result (int) back to the original controller:

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

        // Return int back to original MVC conroller
    }

Have no idea how to proceed, any help appreciated.

Paolo B
  • 3,026
  • 5
  • 21
  • 43

3 Answers3

8

You shouldn't redirect with POST, a redirect almost always uses GET, but you don't want to redirect to an API anyway: what is the browser going to do with the response?

You'll have to perform the POST from your MVC controller and return the data.

Something like this:

[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);
    }           
}
Community
  • 1
  • 1
CodeCaster
  • 147,647
  • 23
  • 218
  • 272
4

Your Web API controller shouldn't be doing much itself. In an application that has proper Separation of Concerns, your processing should be done elsewhere. For example:

This might be in your domain model.

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

Part of your Web API

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

Then calling in your MVC controller, no need to call the Web API. Just call the method it calls directly.

[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();
}
mason
  • 31,774
  • 10
  • 77
  • 121
0

Using this in 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();
}
derHugo
  • 83,094
  • 9
  • 75
  • 115
Silpa
  • 1
  • 1