【发布时间】:2021-12-20 12:54:56
【问题描述】:
这是一个简化的代码隐藏:
[BindProperty(SupportsGet = true)]
public int ProductId { get; set; }
public Product Product { get; set; }
public void OnGet()
{
Product = ProductService.Get(ProductId)
}
public IActionResult OnPost()
{
if (!User.Identity.IsAuthenticated)
{
retrun Redirect("/login");
}
// Add product to user favorite list
// Then how to redirect properly to the same page?
// return Redirect("/product") is not working
// Calling OnGet() does not work
}
这是相应的简化 Razor 页面:
@page "/product/{id}"
@model Product
<div>
@Model.Title
</div>
我无法正确重定向用户。如果我不返回IActionResult,那么我的Redirect("/login") 将不起作用,并且我得到@Model.Title 的空引用异常。
如果我使用IActionResult,那么我的Redirect("/login") 可以工作,但是在用户登录并将产品添加到收藏夹后,我将用户返回到同一页面的代码失败并且OneGet 不会被调用。
【问题讨论】:
-
注意:为了防止重定向攻击,当检测到用户未通过身份验证并重定向到登录页面时,请使用 LocalRedirect()。 LocalRedirect("/login") 确保您使用本地路径并保护您免受篡改查询字符串返回 url 参数
标签: c# asp.net-core razor razor-pages