ValidateAntiForgeryToken返回状态码400

时间:2018-12-30 12:53:07

标签: c# asp.net-core asp.net-core-mvc

问题是,如果我尝试使用ValidateAntiForgeryToken进行操作,则返回状态码400。为什么找不到我的视图页面?

控制器:

public IActionResult Edit(int id) {
    var model = this.categoryService.GetById(id);
    return View(model);
}

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Edit(CategoriesViewModel model) {
    if (ModelState.IsValid) {
        this.categoryService.Update(model);
        return RedirectToAction(nameof(Category));
    }

    return this.View(model.Id);
}

查看:

@using CakeStore.App.Areas.Admin.Models.Categories;
@model CategoriesViewModel
@{
    ViewData["Title"] = "Edit";
    Layout = "~/Areas/Admin/Views/Shared/_AdminLayout.cshtml";        
}

<h1 class="text-center text-header-page">Edit Category</h1>
<hr class="hr-admin-divider" />
<form class="mx-auto w-50 form-horizontal" method="post" action="Edit">
    <div asp-validation-summary="ModelOnly" class="text-danger"></div>
    <div class="form-group">
        <input asp-for="@Model.Id" type="hidden" name="id" value="@Model.Id"/>
    </div>
    <div class="form-group">
        <label asp-for="@Model.Name"></label>
        <input asp-for="@Model.Name" type="text" value="@Model.Name" class="form-control" id="name" name="name">
        <span asp-validation-for="@Model.Name" class="text-danger"></span>
    </div>
    <div class="button-holder d-flex justify-content-center">
        <button type="submit" class="btn button-black-white">Edit</button>
    </div>
</form>

型号:

public class CategoriesViewModel {
    public int Id { get; set; }
    [Required]
    [StringLength(22,MinimumLength =3,ErrorMessage =AdminConstants.NameRange)]
    public string Name { get; set; }
}

1 个答案:

答案 0 :(得分:0)

您没有通知表单包含令牌。以您的形式尝试:

<form asp-antiforgery="true" class="mx-auto w-50 form-horizontal" method="post" action="Edit">

注意:请记住,必须使用@addTagHelper指令才能使用“ asp-antiforgery”