ASP.NET Core中从HttpGet Action Method重定向至带参数的HttpPost Action Method
在ASP.NET Core中从HttpGet重定向到HttpPost并传递参数的实现方案
直接通过标准重定向方法(比如RedirectToAction)无法直接从HttpGet动作跳转到HttpPost动作,因为重定向本质会触发浏览器发起新的GET请求,无法直接触发POST请求。但可以通过以下两种间接方式实现需求:
方法一:借助自动提交的表单传递参数
在HttpGet方法中将参数传递给视图,视图渲染包含隐藏参数的表单,通过JavaScript自动提交表单到目标HttpPost方法。
代码示例
HttpGet动作方法
[HttpGet] public IActionResult MyGetMethod(int id, string name) { // 将参数传递给视图 ViewData["Id"] = id; ViewData["Name"] = name; return View("RedirectToPost"); }
重定向视图(RedirectToPost.cshtml)
<form id="autoSubmitForm" asp-action="MyPostMethod" asp-method="post"> <input type="hidden" name="id" value="@ViewData["Id"]" /> <input type="hidden" name="name" value="@ViewData["Name"]" /> </form> <script> // 页面加载完成后自动提交表单 document.addEventListener('DOMContentLoaded', () => { document.getElementById('autoSubmitForm').submit(); }); </script>
HttpPost动作方法
[HttpPost] public IActionResult MyPostMethod(int id, string name) { // 处理业务逻辑 return View(); }
方法二:使用TempData临时存储参数
将参数存入TempData(临时数据容器,默认依赖Session),重定向到中间GET方法后,再通过表单自动提交到HttpPost方法并读取TempData中的参数。
代码示例
初始HttpGet动作方法
[HttpGet] public IActionResult MyGetMethod(int id, string name) { TempData["Id"] = id; TempData["Name"] = name; return RedirectToAction("RedirectToPost"); } // 中间GET方法,用于渲染提交表单的视图 [HttpGet] public IActionResult RedirectToPost() { return View(); }
重定向视图(RedirectToPost.cshtml)
<form id="autoSubmitForm" asp-action="MyPostMethod" asp-method="post"> <input type="hidden" name="id" value="@TempData["Id"]" /> <input type="hidden" name="name" value="@TempData["Name"]" /> </form> <script> document.addEventListener('DOMContentLoaded', () => { document.getElementById('autoSubmitForm').submit(); }); </script>
HttpPost动作方法
[HttpPost] public IActionResult MyPostMethod(int id, string name) { // 处理业务逻辑 return View(); }
注意事项
- 使用
TempData时需确保项目已启用Session:在Program.cs中添加builder.Services.AddSession();和app.UseSession();配置。 - 敏感参数优先使用表单隐藏字段传递,避免
TempData存储带来的安全风险。 - 自动提交表单的方式对用户透明,仅会产生一次页面跳转过程。
内容的提问来源于stack exchange,提问作者Mahmood Qanbary
相关产品推荐
相关产品推荐

