gpt4 book ai didi

asp.net-mvc - 从 MVC POST 操作方法调用 Web API 并接收结果

转载 作者:行者123 更新时间:2023-12-04 22:20:11 24 4
gpt4 key购买 nike

我正在尝试从 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")
}

我希望将上面的MyList发送到Web Api进行处理,然后它将结果(int)发送回原始 Controller :
// POST api/values
public int Post([FromBody]List<string> value)
{
// Process MyList

// Return int back to original MVC conroller
}

不知道如何进行,任何帮助表示赞赏。

最佳答案

您不应该使用 POST, a redirect almost always uses GET 进行重定向,但无论如何您也不想重定向到 API:浏览器将如何处理响应?

您必须执行 POST from your MVC controller and return the data

像这样的东西:

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

关于asp.net-mvc - 从 MVC POST 操作方法调用 Web API 并接收结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28382607/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com