[英]C# - my ASP.NET MVC page always returns null to my JSON POST request
我有一個客戶端會使用 JSON 將一些字符串數據發送到我的 web 頁面,但是當我發布它時,它總是出於某種原因返回 null。
我的帖子有什么問題嗎?
客戶:
public async Task TesteAsync(string numeroserie)
{
try
{
var json = Newtonsoft.Json.JsonConvert.SerializeObject(numeroserie);
var data = new System.Net.Http.StringContent(json, Encoding.UTF8, "application/json");
var url = "https://localhost:44336/Home/Receive";
var client = new HttpClient();
var response = await client.PostAsync(url, data);
string result = response.Content.ReadAsStringAsync().Result;
MessageBox.Show(result);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
return;
}
}
服務器端:
[System.Web.Http.HttpPost]
public string Receive(string json)
{
return json;
}
我的服務器正在使用 ASP.NET MVC。
更新:我最終要做的是向我的網絡服務器發送一個字符串,然后將其返回給客戶端。 我對 json 沒有經驗,所以我不知道我所做的是否正確
看。 首先讓我們檢查 http 請求。
string url = "YourURL";
string body = JsonConvert.SerializeObject(BodyModel);
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url)
{
Content = new StringContent(body, Encoding.UTF8, "application/json")
};
HttpResponseMessage response = await client.SendAsync(request);
if ((int)response.StatusCode == 200)
{
string responseString = await response.Content.ReadAsStringAsync();
ResponseModel responseModel = JsonConvert.DeserializeObject<ResponseModel>(responseString);
}
現在讓我們對您的 controller 進行一些更改。
[HttpPost]
public JsonResult Receive([FromBody] YourJsonModel parameters)
{
//Do logic
return Json(YourResponseModel);
}
這是您想要傳遞字符串並將其作為字符串獲取的情況。 在您的 controller 中,您可以使用 [FromQuery] 或只留下字符串都可以。
[HttpPost]
public string SomeAction(string data) // public string SomeAction([FromQuery] string data)
{
return data;
}
這是請求
string url = "http://localhost:15832/YOURCONTROLLERNAME/SomeAction?data=YOURSTRINGVALUE";
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url)
{
Content = new StringContent("", Encoding.UTF8, "application/json")
};
HttpResponseMessage response = await client.SendAsync(request);
if ((int)response.StatusCode == 200)
{
string responseString = await response.Content.ReadAsStringAsync(); // here is your response as string
}
PS 如果您不發送正文,您可以將操作類型更改為 HttpGet。 因為它對你的任務很舒服。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.