我想使用 POST 方法将 JSON 数据发送到 razor 页面:
https://localhost:port/Post
并获得 JSON 输出。
例如:
我想以 JSON 形式传递用户名和电子邮件:
{"username":"test","email":"[email protected]"}
到Post.cshtml页面的onPost方法:
https://localhost:44363/Post
:
public JsonResult OnPost([FromForm] 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);
}
我在 WinForms 中使用 HttpClient 调用此 POST 方法:
HttpClient client = new HttpClient();
Dictionary<String, String> dict1 = new Dictionary<String, String>();
dict1.Add("username", "test");
dict1.Add("email", "[email protected]");
String JSON = JsonConvert.SerializeObject(dict1);
HttpResponseMessage Result;
Result = client.PostAsync("https://localhost:44363/Post", new StringContent(JSON, Encoding.UTF8, "application/json")).Result;
String json = Result.Content.ReadAsStringAsync().Result;
Dictionary<String, String> dict2 = JsonConvert.DeserializeObject<Dictionary<String, String>>(json);
但是我收到了
bad request 400
错误。
我也尝试过
FromBody
为: public JsonResult OnPost([FromBody] Dictionary<String, String> FormValues)
但 onPost
不执行。
但是,
OnGet
方法运行良好:
public JsonResult OnGet()
{
Dictionary<String, String> dict = new Dictionary<String, String>();
dict.Add("username", "test");
dict.Add("email", "[email protected]");
return new JsonResult(dict);
}
对于
HttpClient
:
HttpClient client = new HttpClient();
HttpResponseMessage Result;
Result = client.GetAsync("https://localhost:44363/Post").Result;
String json = Result.Content.ReadAsStringAsync().Result;
Dictionary<String, String> dict2 = JsonConvert.DeserializeObject<Dictionary<String, String>>(json);
Razor 页面中的 POST 处理程序默认启用请求验证。这是为了防止跨站点请求伪造。通常,建议是在请求中包含验证令牌,但在您的情况下,最简单的解决方案是在 PageModel 级别禁用对令牌的检查:
[IgnoreAntiforgeryToken(Order = 1001)]
public class PostModel : PageModel
{
...
顺便说一句,如果您要发布 JSON,则需要在处理程序参数上使用
FromBody
属性,而不是 FromForm
。