Pao*_*o B 4 asp.net-mvc asp.net-mvc-4 asp.net-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")
}
Run Code Online (Sandbox Code Playgroud)
我希望将上面的MyList发送到Web Api进行处理,然后将结果(int)发送回原始控制器:
// POST api/values
public int Post([FromBody]List<string> value)
{
// Process MyList
// Return int back to original MVC conroller
}
Run Code Online (Sandbox Code Playgroud)
不知道如何继续,任何帮助表示赞赏.
你不应该使用POST重定向,重定向几乎总是使用GET,但你不想重定向到API:浏览器将如何处理响应?
像这样的东西:
[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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21743 次 |
| 最近记录: |