You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Razor Pages调用OnPost接收JSON返回400错误该如何解决?

问题原因说明
  1. 使用[FromForm]特性时,接口仅支持application/x-www-form-urlencoded类型的表单提交,你当前客户端发送的是application/json类型的JSON数据,参数无法绑定因此返回400错误。
  2. 修改为[FromBody]后方法不执行,是因为Razor Page默认开启了防伪令牌验证,非前端表单提交的请求未携带合法防伪令牌时,会被框架直接拦截,不会进入接口方法。

解决方案

方案1:保留客户端JSON提交逻辑

无需修改客户端现有代码,仅调整后端配置即可:

  1. 在Post.cshtml.cs对应的PageModel类上添加[IgnoreAntiforgeryToken]特性,关闭当前页面的防伪令牌验证:
[IgnoreAntiforgeryToken]
public class PostModel : PageModel
{
    // 原有类代码
}
  1. 调整OnPost方法参数特性为[FromBody]:
public JsonResult OnPost([FromBody] Dictionary<String, String> FormValues)
{
    String username = FormValues["username"];
    String email = FormValues["email"];

    Dictionary<String,String> dict = new Dictionary<String, String>();
    dict.Add("username", username);
    dict.Add("email", email);
    return new JsonResult(dict);
}

方案2:调整客户端为表单提交

保留后端原有[FromForm]逻辑,修改客户端提交方式:
将StringContent替换为FormUrlEncodedContent,无需手动序列化JSON:

HttpClient client = new HttpClient();
Dictionary<String, String> dict1 = new Dictionary<String, String>();
dict1.Add("username", "test");
dict1.Add("email", "test@mail.com");

HttpResponseMessage Result = client.PostAsync("https://localhost:44363/Post", new FormUrlEncodedContent(dict1)).Result;
String json = Result.Content.ReadAsStringAsync().Result;
Dictionary<String, String> dict2 = JsonConvert.DeserializeObject<Dictionary<String, String>>(json);

注:本方案同样需要给PageModel添加[IgnoreAntiforgeryToken]特性关闭防伪验证


额外注意事项
  • HttpClient实例建议全局复用,不要每次请求都新建,避免占用过多套接字资源导致性能问题。
  • 尽量使用async/await写法代替.Result同步阻塞调用,避免出现线程死锁问题。

内容的提问来源于stack exchange,提问作者Computer User

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 20:15:05