XHR POST: to API Controller works, to Razor Page fails

拥有回忆 提交于 2020-01-16 09:01:27

问题


I have a standard ASP.NET Core Web application created from the Visual Studio template. I have a razor page which issues an XHR POST request with a payload upon a change event.

If I make the url of the request an api controller in the application (i.e. under Controllers folder), the request succeeds.

If I make the same request, same payload to a razor page method (under Pages folder), it fails with http 400.

Both methods have the same signature.

Can anyone describe why the behaviour is different?

I would essentially like to use the facility in razor pages to POST to a handler method from an XHR.

UserController.cs

namespace Athena.Web.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        public void Post([FromBody]object postedObj)
        {
            ...
        }
    }
}

Usr.cshtml.cs

namespace Athena.Web.Pages.Users
{
    public class UsrModel : PageModel
    {
        public void OnPostActionHere([FromBody]object postedObj)
        {
            ...        
        }

        public void OnPost([FromBody]object postedObj)
        {
            ...
        }
    }
}

Usr.cshtml

@page "{handler?}"
@model Athena.Web.Pages.Users.UsrModel
@{
    ViewData["Title"] = "Edit";
}

<h1>User</h1>

I can't post the XHR call because it's coming from a third-party Syncfusion control but the calling page is basically:

Index.cshtml

<ejs-grid id="grid">
    <e-data-manager updateUrl="/api/User" insertUrl="/Home/Usr" adaptor="UrlAdaptor">
...
</ejs-grid>


回答1:


XHR Post requests invariably fail when targeted at a Razor Page handler method with a 400 Bad Request because you haven't included the request verification token in the request, either as a form field, or a header.

https://www.mikesdotnetting.com/article/336/ajax-posts-in-razor-pages-and-http-400-errors

the easiest way to generate a token is by including a <form> element with the method set to post, and then you can include the token in the request:

$.ajax({
    type: "POST",
    url: "/",
    data: { foo: "bar" },
    headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
    success: function (response) {


来源:https://stackoverflow.com/questions/58034449/xhr-post-to-api-controller-works-to-razor-page-fails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!