Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 剃须刀页面-使用“剃须刀”时出现400错误;行动“;单击包装在表单中的按钮时重定向到url的标记_C#_Asp.net Core_Razor_Razor Pages - Fatal编程技术网

C# 剃须刀页面-使用“剃须刀”时出现400错误;行动“;单击包装在表单中的按钮时重定向到url的标记

C# 剃须刀页面-使用“剃须刀”时出现400错误;行动“;单击包装在表单中的按钮时重定向到url的标记,c#,asp.net-core,razor,razor-pages,C#,Asp.net Core,Razor,Razor Pages,我在我的页面模型中有一个属性Url,我已将其设置为[BindProperty]。此属性包含用户单击Back按钮时要重定向到的url。然而,当我点击后退按钮时,我得到一个400错误,即使我可以看到url字符串已正确添加到url 如果我只是刷新页面,那么我希望重定向到的页面将按预期加载 为什么我会有400个错误?我怎样才能阻止它发生 cshtml页面: @page "{id:int}" @model AppName.AppVariablesModel @{ ViewDat

我在我的页面模型中有一个属性
Url
,我已将其设置为
[BindProperty]
。此属性包含用户单击
Back
按钮时要重定向到的url。然而,当我点击后退按钮时,我得到一个400错误,即使我可以看到url字符串已正确添加到url

如果我只是刷新页面,那么我希望重定向到的页面将按预期加载

为什么我会有400个错误?我怎样才能阻止它发生

cshtml页面:

@page "{id:int}"
@model AppName.AppVariablesModel
@{
    ViewData["Title"] = "AppVariables";
}
<br />
<h2 style="text-align:center">App Variables</h2>
<br/>
<table style="margin-left:auto; margin-right:auto; cursor:default; width:50%;" class="table-bordered center">
    @foreach (var dict in Model.AppVariablesDict)
    {
        <tr style="cursor:default;">
            <th style="color:white;">@dict.Key</th>
            <td style="color:black;">@dict.Value</td>
        </tr>
    }
</table>
<br/>
<form action="@Model.Url" method="POST">
    <body style="text-align:center">
        <button type="submit" style="color:black;" class="btn-sm ml-auto mr-1" title="Back">
            Back
        </button>
    </body>
</form>

namespace AppName
{
    public class AppVariablesModel : PageModel
    {
       [BindProperty]
        public string Url { get; set; }
    }

public void OnGet(int id, string db, string server, string url)
        {
           Url = url;
        }

您的表单正在使用http POST谓词,但您正在尝试使用GET谓词执行命令。它不能以这种方式在表格上布线。你错配了

需要注意的关键事项:

form action=“@Model.Url”method=“POST

公共空间OnGet


将表单方法更改为使用Get,或者实现OnPost()方法而不是OnGet

此外,Razor页面会自动受到XSRF/CSRF的保护,如果要执行
POST
方法,还需要提供AntiForgeryToken,请参阅

因此,解决方案是,您需要为url实现一个
OnPost
处理程序,并在表单中添加
@Html.AntiForgeryToken()

CalculationVariablesModel.cshtml

<form action="@Model.Url" method="Post">
    @Html.AntiForgeryToken() 
</form>

你能给我们举个例子说明什么是
@Model.Url
吗?如果你想重定向Url,你不能使用
type=“submit”
将转到
onPost
处理程序提交表单。您想做什么?.Net core默认情况下通过FormTagHelper自动注入反伪造令牌,因此您无需执行此操作。或者,您必须手动选择退出生成。上面展示的方法类似于全框架MVC站点,但如果要走这条路,还必须使用[ValidateJsonAntiForgeryToken]属性来修饰post动词。
public IActionResult OnPost()
{
    //...
    return Page();
}