【发布时间】:2021-07-01 08:11:40
【问题描述】:
设置cookie后我无法返回任何地方,cookie设置正确但设置cookie后,它不会重定向到任何地方。
这是我的代码:
<a onclick="changeGuestCity(@city.LocationId)">
<span class="font-400 opacity-70">@city.LocationTitle</span>
</a>
这是 JavaScript 的函数:
<script>
function changeGuestCity(id) {
$.get("/Home/ChangeGuestCity/" + id);
}
</script>
这是我的函数,但不会重定向到索引或其他任何地方:
public IActionResult Index()
{
return View();
}
public IActionResult ChangeGuestCity(int? id)
{
if (id == null)
return Redirect("/");
CookieOptions cityCookie = new CookieOptions()
{
Expires = DateTime.Now.AddDays(30)
};
Response.Cookies.Append("city", id.ToString(), cityCookie);
return Redirect("/");
}
【问题讨论】:
-
浏览器控制台有错误吗?
-
ajax 请求中的重定向仅将响应重定向到该请求。根据您似乎想要的流程,不确定您为什么在这里使用 ajax。可以用
location.href = "/Home/ChangeGuestCity/" + id做你想做的事 -
@Crowcoder JS 代码工作正常,它将 LocationId 发送到我的控制器的方法 (ChangeGuestCity),并且 ChangeGuestCity 的方法也设置了 cookie。但返回不起作用!
-
您不应该将 id 设置为查询参数,还是在 ChangeGuestCity 实现中指定 id 是 url 段?例如
/Home/ChangeGuestCity/?id="+id或[Route("/Home/ChangeGuestCity/{id}")] -
该操作将正确返回重定向,但您在 JavaScript 中的 AJAX 调用不会尊重该结果。如果您想通过 JavaScript 调用端点,则必须使用 JavaScript 手动重定向客户端。
标签: javascript c# jquery asp.net-mvc asp.net-core