繁体   English   中英

如何在ASP.NET Core中发布JSON有效负载时解决“错误请求(400)”错误?

[英]How to fix 'Bad Request (400)' error when POSTing JSON payload in ASP.NET Core?

我正在开发实现命名处理程序方法的剃刀页面。 我将一些JSON编码的数据发布到命名的处理程序方法中。 但是,我得到了400错误的请求响应。

到目前为止,我尝试使用不同的JSON负载和不同的方法签名,但是可惜没有任何效果。

这是我的方法的缺点:

        [HttpPost]
        public IActionResult OnPostContextFreeGrammarPartial() {
            var grammarModel = new ContextFreeGrammarModel();

            return new PartialViewResult() {
                ViewName = "_ContextFreeGrammar",
                ViewData = new ViewDataDictionary<ContextFreeGrammarModel>(ViewData, grammarModel)
            };
        }

这是一个示例请求:

发送的HTTP请求

我期望处理程序方法能够成功执行,但是服务器或浏览器只是在该方法开始执行之前就抛出400响应。

我想念什么?

您应该将数据传递给OnPostContextFreeGrammarPartial,我认为grammarModel为null! 试试这个我认为这是有帮助这里

    [HttpPost]
[AutoValidateAntiforgeryToken]
        public IActionResult OnPostContextFreeGrammarPartial([FromBody]ContextFreeGrammarModel item) 
        {
            var grammarModel = new ContextFreeGrammarModel();

            return new PartialViewResult() {
                ViewName = "_ContextFreeGrammar",
                ViewData = new ViewDataDictionary<ContextFreeGrammarModel>(ViewData, grammarModel)
            };
        }

并且在startup.cs中:

services.AddMvc(options =>
        {
            options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
        });

克里斯·普拉特(Chris Pratt)的评论解释了这个问题。 请求标头中缺少反伪造令牌-Razor页面上的发布请求所需。

他还建议使用控制器而不是Razor页面。

编辑

在启动过程中向服务添加IgnoreAntiforgeryToken筛选器也解决了该问题。

            services.AddMvc()
                .AddRazorPagesOptions(options => {
                    options.Conventions.ConfigureFilter(new IgnoreAntiforgeryTokenAttribute());
                }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM