在asp.net core中使用带有对象参数值的GetAsync方法,需要通过构建HttpClient来实现。具体实现步骤如下:
HttpClient client = new HttpClient();
Uri uri = new Uri("http://example.com/api"); MyObject myObject = new MyObject { Id = 1, Name = "example" };
string json = JsonConvert.SerializeObject(myObject);
HttpContent httpContent = new StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.GetAsync(uri + "?param=" + httpContent);
string result = await response.Content.ReadAsStringAsync();
完整代码示例如下:
using Newtonsoft.Json; using System; using System.Net.Http; using System.Text; using System.Threading.Tasks;
public class MyObject { public int Id { get; set; } public string Name { get; set; } }
public class Program { static async Task Main() { HttpClient client = new HttpClient(); Uri uri = new Uri("http://example.com/api"); MyObject myObject = new MyObject { Id = 1, Name = "example" }; string json = JsonConvert.SerializeObject(myObject); HttpContent httpContent = new StringContent(json, Encoding.UTF8, "application/json"); HttpResponseMessage response = await client.GetAsync(uri + "?param=" + httpContent); string result = await response.Content.ReadAsStringAsync();
// do something with result
}
}
注意:在使用GetAsync方法时如果携带的参数值较大,也可以考虑使用POST方法发送请求。