shertu
shertu

Reputation: 511

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

I am developing a razor page which implements a named handler method. I post some JSON encoded data to the named handler method. However, I get a 400 bad request response in response.

I have tried using different JSON payloads and different method signatures so far but alas, nothing has worked.

Here is a snub of my method:

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

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

And here is an example request:

The sent HTTP request

I am expecting the handler method to be successfully executed but instead the server or browser simply throws a 400 response before the method even begins to execute.

What am I missing?

Upvotes: 0

Views: 5994

Answers (2)

shertu
shertu

Reputation: 511

Chris Pratt's comment explains the issue. The anti-forgery token was missing from the request header - which is required for post requests on Razor pages.

He also suggested using a Controller instead of a Razor page.

EDIT

Adding a IgnoreAntiforgeryToken filter to the services during startup also fixed the problem.

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

Upvotes: 0

Faraz
Faraz

Reputation: 883

You should pass data to OnPostContextFreeGrammarPartial and I think grammarModel is null! Try this I think it's helpful here

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

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

And also in startup.cs:

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

Upvotes: 2

Related Questions