【发布时间】:2022-01-12 06:40:25
【问题描述】:
我想使用 POST 方法将 JSON 数据发送到剃须刀页面:https://localhost:port/Post 并获得 JSON 输出。
例如:
我想将用户名和电子邮件作为 JSON 传递:
{"username":"test","email":"test@mail.com"}
到 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", "test@mail.com");
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", "test@mail.com");
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);
【问题讨论】:
标签: asp.net razor-pages