【问题标题】:Why OnPost is not getting hit without "@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers" in ASP.NET Core version 5.0为什么在 ASP.NET Core 5.0 版中没有“@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers”时 OnPost 不会受到打击
【发布时间】:2021-09-27 20:03:56
【问题描述】:

我正在使用 ASP.NET CORE 5.0 版,并且正在为我的 Web UI 使用剃须刀页面。我在使用 HTML 中具有以下结构的简单 OnPost 方法时遇到问题:

@page

@model EmptyOne.Web.Pages.SaysHelloModel
@{
}
<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Search</title>
</head>
<body>
    <p>Enter the name you wanna say hello two ;)</p>

    <form method="post">
        Search term:
        <input name="nameToHello" />
        <input type="submit" />
    </form>

    @* some logic to say hello if model is not null... *@
</body>
</html>

这是我的页面模型类:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace EmptyOne.Web.Pages
{
    public class SaysHelloModel : PageModel
    {
        public string guysName { get; set; }
        public void OnGet()
        {
            
        }

        
        public IActionResult OnPost(string nameToHello)
        {
            guysName = nameToHello;
            return Page();
        }
    }
}

当我尝试点击它时,它会返回一个 HTTP 400 状态核心和一个空白页面,但由于某种原因,当我添加这个助手时:

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

效果很好!

最终的工作视图(我没有更改页面模型类中的任何内容):

@page

@model EmptyOne.Web.Pages.SaysHelloModel
@{
}
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Search</title>
</head>
<body>
    <p>Enter the name you wanna say hello two ;)</p>

    <form method="post">
        Search term:
        <input name="nameToHello" />
        <input type="submit" />
    </form>

    @* some logic to say hello if model is not null... *@
</body>
</html>

那么任何人都可以向我解释为什么会这样吗?我查找了一个 ASP.NET Core 5.0 版代码示例并看到了这个帮助程序。我是否以任何方式使用这个助手?它与向我的页面处理程序发送 HTTP 发布请求有什么关系?

【问题讨论】:

    标签: httprequest razor-pages asp.net-core-5.0 asp.net-core-tag-helpers


    【解决方案1】:

    Razor Pages 默认包含anti-CSRF mechanism, known as request verification。它依赖于一个令牌,该令牌应用于随每个 POST 请求发送的隐藏表单字段。隐藏表单域由form tag helper 自动生成。如果您在帖子中省略了令牌值,例如通过禁用表单标签助手,框架会返回 400 Bad Request。

    【讨论】:

    • 谢谢,但我不完全理解这里的逻辑。因为一开始就没有辅助参考。如果缺少它会导致 HTTP 发布请求失败,是否应该在剃刀页面创建时间添加它?或者你的意思是我没有使用其他标签助手,它为模型制作自动表单;因此,我应该添加这个助手。我做对了吗?
    • addTagHelper 调用应该进入 ViewImports 文件,这样就不需要在每个页面中使用它:learnrazorpages.com/razor-pages/files/viewimports
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-02
    • 2021-03-04
    • 1970-01-01
    • 2021-10-21
    • 1970-01-01
    • 2021-09-23
    相关资源
    最近更新 更多