发布表单时获取HTTP错误400

时间:2019-04-25 01:43:29

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

我有一个asp.net核心剃须刀页面,其中有一个简单的表单,要求用户提供电子邮件地址和提交按钮。输入电子邮件并单击“提交”按钮时,总是出现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
        }

    }
}

错误消息(屏幕截图): enter image description here

2 个答案:

答案 0 :(得分:0)

如下编写您的OnGet()OnPost方法。这将向您显示视图上的确切错误。

public IActionResult OnGet()
{
    return Page();
}

public IActionResult OnPost()
{
    if (!ModelState.IsValid)
    {
        return Page();
    }

    var emailAddress = Request.Form["emailaddress"];
    // do something with emailAddress
}

答案 1 :(得分:0)

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

我只是在表单标签内添加了@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>