【问题标题】:Getting HTTP ERROR 400 when form gets posted发布表单时收到 HTTP ERROR 400
【发布时间】:2019-04-25 01:43:29
【问题描述】:

我有一个 asp.net core razor 页面,其中有一个简单的表单,要求输入用户电子邮件地址和提交按钮。当我输入电子邮件并单击提交按钮时,我总是收到 400 错误

HTTP 错误 400

我不确定我在这里做错了什么。我尝试在 OnPost 方法中放置一个断点,但我什至没有达到那个点。

下面是我的代码:

Homie.cshtml

@page
@model WebApplication1.Pages.HomieModel
@{
    ViewData["Title"] = "Homie";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h1>Homie</h1>

<form method="post">
    <input type="email" name="emailaddress">
    <input type="submit">
</form>

Homie.cshtml.cs

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

namespace WebApplication1.Pages
{
    public class HomieModel : PageModel
    {
        public void OnGet(string n)
        {
        }

        public void OnPost()
        {
            var emailAddress = Request.Form["emailaddress"];
            // do something with emailAddress
        }

    }
}

错误消息(屏幕截图):

【问题讨论】:

  • 除了 400 之外,您在响应中看到任何其他信息吗?
  • @ChetanRanpariya no.. 没有
  • 你能调试OnPost的代码吗?您是否在浏览器中看到此错误?如果浏览器出现错误,您可以分享屏幕截图吗?
  • @ChetanRanpariya 添加了屏幕截图。

标签: c# asp.net-core razor-pages


【解决方案1】:

我发现了问题所在。 问题是它缺少表单中的防伪令牌。

我只是在表单标签中添加了@Html.AntiForgeryToken();,现在一切正常。

Homie.cshtml

@page
@model WebApplication1.Pages.HomieModel
@{
    ViewData["Title"] = "Homie";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h1>Homie</h1>

<form method="post">
    <input type="email" name="emailaddress">
    <input type="submit">
    @Html.AntiForgeryToken();
</form>

似乎当您有一个 asp.net 核心 mvc 应用程序并在其中添加一个剃须刀页面并尝试创建一个表单时,它不会默认为 asp.net 核心的Form Tag Helper

如果您将此行添加到 Homie.cshtml 页面,@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers 它将自动使其成为表单标签助手。见here

所以我将代码 Homie.cshtml 更改为:

Homie.cshtml

@page
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@model WebApplication1.Pages.HomieModel
@{
    ViewData["Title"] = "Homie";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h1>Homie</h1>

<form method="post">
    <input type="email" name="emailaddress">
    <input type="submit">
</form>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-10
    • 2014-12-04
    • 2012-01-12
    • 1970-01-01
    • 2021-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多