从 HTTP 请求接收 JSON 数据

我有一个正常工作的 Web 请求,但它只是返回状态 OK,但我需要的对象,我要求它返回。我不确定如何获得我所请求的 json 值。我是新使用的对象 HttpClient,是否有一个属性我错过了?我真的需要返回物体。谢谢你的帮助

使调用运行良好返回状态 OK。

HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var responseMsg = client.GetAsync(string.Format("http://localhost:5057/api/Photo")).Result;

Api 获取方法

//Cut out alot of code but you get the idea
public string Get()
{
return JsonConvert.SerializeObject(returnedPhoto);
}
420649 次浏览

如果你指的是系统。网。HttpClient 在。NET 4.5,您可以使用 内容属性作为从 HttpContent派生的对象获取 GetAsync 返回的内容。然后,您可以使用 读取 StringAsync方法将内容读取到字符串中,或者使用 ReadAsStreamAsync方法将内容读取为流。

HttpClient类文档包括以下示例:

  HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("http://www.contoso.com/");
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();

@ Panagiotis Kanavos的答案为基础,这里有一个工作方法作为例子,它也将以对象而不是字符串的形式返回响应:

using System.Text;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json; // Nuget Package


public static async Task<object> PostCallAPI(string url, object jsonObject)
{
try
{
using (HttpClient client = new HttpClient())
{
var content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json");
var response = await client.PostAsync(url, content);
if (response != null)
{
var jsonString = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<object>(jsonString);
}
}
}
catch (Exception ex)
{
myCustomLogger.LogException(ex);
}
return null;
}

请记住,这只是一个示例,您可能希望使用 HttpClient作为共享实例,而不是在 using 子句中使用它。

我通常会这么做,类似于回答第一个问题:

var response = await httpClient.GetAsync(completeURL); // http://192.168.0.1:915/api/Controller/Object


if (response.IsSuccessStatusCode == true)
{
string res = await response.Content.ReadAsStringAsync();
var content = Json.Deserialize<Model>(res);


// do whatever you need with the JSON which is in 'content'
// ex: int id = content.Id;


Navigate();
return true;
}
else
{
await JSRuntime.Current.InvokeAsync<string>("alert", "Warning, the credentials you have entered are incorrect.");
return false;
}

其中“ model”是您的 C # model 类。

我认为最捷径是:

var client = new HttpClient();
string reqUrl = $"http://myhost.mydomain.com/api/products/{ProdId}";
var prodResp = await client.GetAsync(reqUrl);
if (!prodResp.IsSuccessStatusCode){
FailRequirement();
}
var prods = await prodResp.Content.ReadAsAsync<Products>();

以下方式对我很有效

public async Task<object> TestMethod(TestModel model)
{
try
{
var apicallObject = new
{
Id= model.Id,
name= model.Name
};


if (apicallObject != null)
{
var bodyContent = JsonConvert.SerializeObject(apicallObject);
using (HttpClient client = new HttpClient())
{
var content = new StringContent(bodyContent.ToString(), Encoding.UTF8, "application/json");
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
client.DefaultRequestHeaders.Add("access-token", _token); // _token = access token
var response = await client.PostAsync(_url, content); // _url =api endpoint url
if (response != null)
{
var jsonString = await response.Content.ReadAsStringAsync();


try
{
var result = JsonConvert.DeserializeObject<TestModel2>(jsonString); // TestModel2 = deserialize object
}
catch (Exception e){
//msg
throw e;
}
}
}
}
}
catch (Exception ex)
{
throw ex;
}
return null;
}

从 MicrosoftSystem.Net.Http.Json安装这个 nuget 包。它包含扩展方法。

然后加入 using System.Net.Http.Json

现在,你可以看到这些方法:

enter image description here

所以你现在可以这样做:

await httpClient.GetFromJsonAsync<IList<WeatherForecast>>("weatherforecast");

资料来源: https://www.stevejgordon.co.uk/sending-and-receiving-json-using-httpclient-with-system-net-http-json

下面的代码用于访问 HttpResponseMessage 并从 HttpContent 提取响应。

string result = ret.Result.Content.ReadAsStringAsync().Result;

将您的 json 转换为与您的业务相一致的结构 在我的例子中,BatchPDF 是一个由 result 变量填充的复杂对象。

BatchPDF batchJson = JsonConvert.DeserializeObject<BatchPDF>(result);


return batchJson;