如何在ASP.NET Core Razor Pages中正确地重定向到同一页面?

3
这里是简化的后端代码:

[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参数的影响。 - Roger
1个回答

3

在 Razor 中,您可以使用 RedirectToPage()。

假设该类名为 IndexModel。

public class IndexModel: PageModel
{
    public IActionResult OnPost()
    {
       if (!User.Identity.IsAuthenticated)
       {
           return 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

       return RedirectToPage("Index");
   }
}

注意:你在代码中拼写了错误的 return,应该是 retrun

更新:你想要遵循 PRG 模型:在 Post 后进行 Redirect 到 Get。

为了将参数传回 OnGet 操作,请执行以下操作:

public void OnGet(int productId)
{
    Product = ProductService.Get(productId)
}

而在你的看法中:

@page "/product/{productId}"

并且在 OnPost 方法中

return RedirectToPage("Index", new { productId = ProductId});

谢谢@Roger。但这意味着我失去了所有的查询字符串和路由数据。我怎么能保留所有的URL?我的意思是,如果我能写RedirectToTheSamePage(),那么我就不用担心所有的URL问题了。 - Ali EXE
谢谢@Roger。我认为你的答案终于解决了一直困扰我的问题。我从未听说过PRG模型。我一直在使用return Page();,现在我想这通常只用于异常情况。我现在要进一步阅读PRG模型了。 - Observer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接