asp.net-mvc 从 MVC POST 操作方法调用 Web API 并接收结果
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28382607/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Call to Web API from MVC POST action method and receive a result
提问by Paolo B
I am trying to call to a Web API from MVC POST action method and receive a result but not sure how, for example:
我正在尝试从 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")
}
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:
我希望将上面的MyList发送到Web Api进行处理,然后它将结果(int)发送回原始控制器:
// 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.
不知道如何进行,任何帮助表示赞赏。
回答by CodeCaster
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?
您不应该使用 POST 重定向,重定向几乎总是使用 GET,但无论如何您都不想重定向到 API:浏览器将如何处理响应?
You'll have to perform the POST from your MVC controller and return the data.
您必须从 MVC 控制器执行POST 并返回数据。
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);
}
}
回答by mason
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:
您的 Web API 控制器本身不应该做太多事情。在具有适当关注点分离的应用程序中,您的处理应该在其他地方完成。例如:
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
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.
然后调用您的 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();
}
回答by Silpa
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();
}

