You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Dotnet 8 Blazor Web App中EditForm未触发CallForm方法问题

Blazor Web App(.NET 8)Contact组件提交失败问题排查

问题现象

点击Send按钮未触发CallForm方法,直接跳转空白页,页面提示:

请求未提供有效的antiforgery token。请添加antiforgery token,或为此端点禁用antiforgery验证。

查看浏览器网络请求,发现POST请求返回BadRequest,Payload中__RequestVerificationToken重复发送两次:

_handler=testForm&__RequestVerificationToken=CfDJ8PrBKUcP_2BApN476NPsIEP8rTXN_zrI4-5nDXMWjirv5ixEAyUkXxxnaXkIwaBbTxESiX9LLr_KiAweW-QhJ4E2DGNYJLBJaLQ__SOz9NIRMR_tl7zCnamZONe7bOcy3e__EaqW4rTDkL-C3VbsFEQ&__RequestVerificationToken=CfDJ8PrBKUcP_2BApN476NPsIEP8rTXN_zrI4-5nDXMWjirv5ixEAyUkXxxnaXkIwaBbTxESiX9LLr_KiAweW-QhJ4E2DGNYJLBJaLQ__SOz9NIRMR_tl7zCnamZONe7bOcy3e__EaqW4rTDkL-C3VbsFEQ

组件代码

@using System.ComponentModel.DataAnnotations
@using System.Net.Mail;
@using System.Net;
@using Microsoft.AspNetCore.Antiforgery
@using Microsoft.AspNetCore.Mvc
@using OneManArmyBlazorWeb.Models
@using OneManArmyBlazorWeb.Services
@using OneManArmyBlazorWeb.Settings

@namespace OneManArmyBlazorWeb.Components.Sections

@inject ILogger<Contact> _logger 
@inject IMailSender _mailSender

<!-- Contact Section -->
<section id="contact" class="contact section">

    <!-- Section Title -->
    <div class="container section-title" data-aos="fade-up">
        <h2>Get in Touch</h2>
        <p>
            Whether you have a question, a project idea, or just want to connect, I’d love to hear from you!
        </p>
    </div><!-- End Section Title -->

    <div class="container" data-aos="fade-up" data-aos-delay="100">

        <EditForm method="post" Model="Model" OnInvalidSubmit="CallForm" FormName="testForm" Enhance action="" class="php-email-form" data-aos="fade-up" data-aos-delay="200">
            @* <DataAnnotationsValidator /> *@
            @* <ValidationSummary /> *@

            <div class="row gy-4">

                <div class="col-md-6">
                    <label for="name-field" class="pb-2">Your Name</label>
                    <input type="text" id="name-field" class="form-control" @bind-value="Model.Name">
                    @* <ValidationMessage For="@(() => Model.Name)" /> *@
                </div>

                <div class="col-md-6">
                    <label for="email-field" class="pb-2">Your Email</label>
                    <input type="email" class="form-control" @bind-value="Model.Email">
                    @* <ValidationMessage For="@(() => Model.Email)" /> *@
                </div>

                <div class="col-md-12">
                    <label for="subject-field" class="pb-2">Subject</label>
                    <input type="text" class="form-control" @bind-value="Model.Subject">
                    @* <ValidationMessage For="@(() => Model.Subject)" /> *@
                </div>

                <div class="col-md-12">
                    <label for="message-field" class="pb-2">Message</label>
                    <textarea class="form-control" @bind="Model.Message" rows="10" id="message-field"></textarea>
                    @* <ValidationMessage For="@(() => Model.Message)" /> *@
                </div>

                <div class="col-md-12 text-center">
                    <div class="loading">Loading</div>
                    <div class="error-message @errorShowClass">@errorMessage</div>
                    <div class="sent-message @successShowClass">Your message was sent successfully!</div>

                    <button type="submit" style="@sendButtonBackgroundColor" disabled=@sendButtonDisabled>@sendButtonMessage</button>
                </div>

            </div>
            <AntiforgeryToken />
        </EditForm>
        
    </div>

</section>
<!-- /Contact Section -->

@code {
    [SupplyParameterFromForm]
    public ContactModel Model { get; set; } = new ();

    public async Task CallForm()
    {
        try
        {
            await _mailSender.SendEmailAsync(Model);

            _logger.LogInformation("Email sent successfully!\nSubject: {Subject}\nName: {Name}\nEmail: {Email}\nMessage: {Message} ", Model.Subject, Model.Name, Model.Email, Model.Message);
        }
        catch (Exception e)
        {
            _logger.LogError("There was an error sending the email: {Error}\nSubject: {Subject}\nName: {Name}\nEmail: {Email}\nMessage: {Message} ",
            e.Message,
            Model.Subject,
            Model.Name,
            Model.Email,
            Model.Message);
        }
    }
}

解决方案

1. 移除手动添加的防伪令牌

Blazor的EditForm在启用Enhance和method="post"时,会自动生成并注入防伪令牌。手动添加<AntiforgeryToken />会导致令牌重复,服务器验证失败。删除该标签即可解决重复问题。

2. 修正表单提交事件绑定

当前使用OnInvalidSubmit="CallForm",该事件仅在表单验证失败时触发。如果需要在验证通过后执行提交逻辑,应改为OnValidSubmit;若无论验证结果都要执行,使用OnSubmit:

<EditForm method="post" Model="Model" OnValidSubmit="CallForm" FormName="testForm" Enhance action="" class="php-email-form" data-aos="fade-up" data-aos-delay="200">

3. 验证模型绑定配置

确保[SupplyParameterFromForm]属性正确应用于Model,且ContactModel的属性与表单输入的绑定逻辑一致(Blazor的@bind-value会自动生成正确的表单字段名,无需手动调整)。

内容的提问来源于stack exchange,提问作者Luca Prodan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 10:05:57