如何在 ASP.NET 中的 PageModel 中处理 fetch post 请求

问题描述 投票:0回答:1

我有一个 Index.cshtml.cs 文件,其 PageModel 代码如下:

namespace DemoApp.Pages
{
    public class IndexModel : PageModel
    {
         public void OnPost() {}
         public void OnGet() {}
         public IActionResult OnPost([FromBody] JObject requestData)
         {
             System.Diagnostics.Debug.WriteLine("Request data = " + requestData);
             return Content("Registration successful");
         }
    }
}

而且,我想像这样处理 Fetch Post 请求

fetch("/Index", {
    method: "POST",
    body: jsondata,
    headers: {
        "Content-Type": "application/json",
    }
})
.then(response => response.text()) 
.then(data => {
    alert(data);
})
.catch(error => {
    console.error("Error:", error);
});

我该怎么做?是不是POST请求的URL不一样,或者处理方式不正确?

c# asp.net asp.net-core razor-pages
1个回答
0
投票

注意:Razor 页面会自动受到 XSRF/CSRF 的保护,这就是为什么您在调试时总是得到 400 响应而无需进入端点的原因

您可以查看此文档相关

在代码中添加这些行:

@Html.AntiForgeryToken()

修改js代码:

    var payload = {
    name: "John", time: "2pm"
};
fetch("/", {
    method: "POST",
    body: JSON.stringify(payload),
    headers: {
        'RequestVerificationToken': document.getElementsByName("__RequestVerificationToken")[0].value,
        'Accept':"*/*",
        'Content-Type': 'application/json'
    }
})

此外,.net core 从 3.x 版本开始使用

System.Text.Json
代替
NewtonSoft.Json
进行序列化/反序列化

不要将数据与JObject绑定,创建一个类用于绑定

public class ViewModel
{
    public string? Name { get; set; }

    public string? Time { get; set; }
}

现在在我这边效果很好:

© www.soinside.com 2019 - 2024. All rights reserved.