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.
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);
}
}
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With