Cannot post JSON to an ASP.NET Core RazorPage handler

给你一囗甜甜゛ 提交于 2020-05-15 05:56:08

问题


I'm working with an ASP.NET Core RazorPage as an alternative to an MVC controller, and I want to be able to submit the client side form via XMLHttpRequest. I've already figured out the XSRF token bits so that passes the muster, but the RazorPages framework doesn't seem to process the inbound JSON payload and bind it to the property as expected.

Some code:

The page's model (.cshtml.cs):

public class IndexModel : PageModel
{
    private Database database;
    private ILogger logger;

    [BindProperty]
    public AddRequestModel MyRequest { get; set; }

    public IndexModel(Database database, ILogger<IndexModel> logger)
    {
        this.database = database;
        this.logger = logger;
    }

    public void OnGet() {}

    public IActionResult OnPostValidate()
    {
        if (ModelState.IsValid)
        {
            // ...
        }

        return new BadRequestObjectResult(ModelState);
    }

    public async Task<IActionResult> OnPutConfirmAsync()
    {
        // ...
    }
}

And the client side post:

const url = "?handler=validate";
const data = { MyRequest: this.fields };
await axios.post(url, data);

I have verified the data is being submitted correctly:

That X-XSRF-TOKEN header is being added by axios before the request is submitted. The fact that the server responds with a list of errors indicates that it's not the XSRF token causing the problem:

Note the MyRequest object does not contain the values from the request payload - it was not bound as expected (FirstName would not return a required error otherwise). How can I tell RazorPages to accept the JSON request and bind it to my property?


回答1:


Use urlsearchparams with formdata.

In this post you can find more information How do I post form data with fetch api?




回答2:


I was able to get the Binding works by adding FromBody similar to how it worked for ASP.NET Web API 2.

    [BindProperty, FromBody]
    public BroadcastMessageEditingViewModel BindingInfo { get; set; }



回答3:


You would be better off posting your data to an API endpoint instead of a page controller. Create a class from ControllerBase and it will handle your JSON post correctly.



来源:https://stackoverflow.com/questions/47783104/cannot-post-json-to-an-asp-net-core-razorpage-handler

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