【问题标题】:How to properly redirect to the same page in ASP.NET Core Razor Pages?如何正确重定向到 ASP.NET Core Razor Pages 中的同一页面?
【发布时间】: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


【解决方案1】:

在 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 之后R重定向到 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 的东西了。
猜你喜欢
  • 2020-11-29
  • 2018-01-31
  • 1970-01-01
  • 2018-10-21
  • 2018-04-05
  • 2018-11-25
  • 2021-02-21
  • 1970-01-01
相关资源
最近更新 更多