PageRemote 属性不发送 __RequestVerificationToken

PageRemote attribute doesn't send __RequestVerificationToken

我正在使用 .NET 6 和剃须刀页面。
POST 方法中的 [PageRemote] 属性没有将 __requestverificationtoken 发送到服务器,我收到错误 400。

这是我的 ViewModel

public class AddCategory
{
    [PageRemote(PageName = "Category", PageHandler = "CheckForTitle",
    HttpMethod = "POST",
    AdditionalFields = "__RequestVerificationToken",
    ErrorMessage = "This title is duplicate")]
    public string Title { get; set; } = null!;
 }

这是我的经纪人

public class CategoryModel : PageModel
{
    [BindProperty]
    public AddCategory Category { get; set; }

    public void OnGet()
    {
    }

    public IActionResult OnPostCheckForTitle(AddCategory category)
    {
        return new JsonResult(category.Title == "a");
    }
}

GET 方法没问题,一切都很好,但是在 POST 方法中 __requestverificationtoken 没有发送到服务器,我收到错误 400。

您尝试验证的 属性 位于嵌套的 属性 上。 AdditionalFields 属性 中列出的所有字段在发布时都将以嵌套的 属性 名称作为前缀,因此请求验证令牌将作为 Category.__RequestVerificationToken 发布。结果请求验证token本身没有找到,请求验证失败导致400状态码。

您应该将单独的字符串 属性 添加到页面模型 Title,然后将 PageRemote 属性应用于该字符串并通过 [=15= 在输入标签助手中引用它].一旦您对提交有效感到满意,就可以将发布的 Title 值分配给 Category 对象中的相关 属性 并照常处理。

public class CategoryModel : PageModel
{
    [BindProperty]
    public AddCategory Category { get; set; }
   
    [BindProperty, PageRemote(PageName = "Category", PageHandler = "CheckForTitle",
    HttpMethod = "POST",
    AdditionalFields = "__RequestVerificationToken",
    ErrorMessage = "This title is duplicate")]
    public string Title { get; set; } = null!;

    public IActionResult OnPostCheckForTitle(AddCategory category)
    {
        return new JsonResult(Title == "a");
    }
}

@Mike Brind 解释得很好。您可以从模型中拆分 属性 并使用 asp-for="PropertyName" 而不是嵌套 属性.

的一种方法

另一种方法是通过指定名称属性来覆盖名称,如下所示:

<form method="post">>
    //if you use method="post", it will auto generate token
    //if you do not use method="post", remember add token like below
    @*@Html.AntiForgeryToken()*@

    <div class="form-group">
    <label asp-for="Category.Title"></label>
                                     //add the name....
    <input asp-for="Category.Title" name="Title" class="form-control" />
    <span asp-validation-for="Category.Title" class="text-danger"></span>
</div>
</form>    
@section Scripts
{
    <partial name="_ValidationScriptsPartial" />    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-ajax-unobtrusive/3.2.6/jquery.unobtrusive-ajax.js" integrity="sha256-v2nySZafnswY87um3ymbg7p9f766IQspC5oqaqZVX2c=" crossorigin="anonymous"></script>        
}