Home > database >  PageRemote attribute doesn't send __RequestVerificationToken
PageRemote attribute doesn't send __RequestVerificationToken

Time:01-30

I'm using .NET 6 and razor pages.
[PageRemote] attribute in POST method doesn't send __requestverificationtoken to server and I get error 400.

This is my ViewModel

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

And this is my handler

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 method is ok and everything is fine, but in POST method __requestverificationtoken doesn't send to the server and I get error 400.

CodePudding user response:

The property that you are trying to validate is on a nested property. All fields listed in the AdditionalFields property will be prefixed with the nested property name when they are posted, so the request verification token will be posted as Category.__RequestVerificationToken. As a result, the request verification token itself is not found, and request verification fails resulting in the 400 status code.

You should add a separate string property to the PageModel, Title, then apply the PageRemote attribute to that and reference it in the input tag helper via asp-for. Once you are happy that the submission is valid, you can assign the posted Title value to the relevant property in your Category object and process as usual.

CodePudding user response:

@Mike Brind has been explained very nice. One way you can split the property from model and use asp-for="PropertyName" instead of nested property.

Another way is just override the name by specifying the name attribute like below:

<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 >
    <label asp-for="Category.Title"></label>
                                     //add the name....
    <input asp-for="Category.Title" name="Title"  />
    <span asp-validation-for="Category.Title" ></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>        
}
  •  Tags:  
  • Related