Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call to Web API from MVC POST action method and receive a result

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.

like image 772
Paolo B Avatar asked Dec 14 '22 16:12

Paolo B


2 Answers

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);
    }           
}
like image 103
CodeCaster Avatar answered Jan 20 '23 14:01

CodeCaster


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();
}
like image 36
mason Avatar answered Jan 20 '23 14:01

mason