I want to send a http request that containing string value to another api. I want to save the incoming response as an entity.
CodePudding user response:
You can try this:
//Yours entity.
MyEntity myEntity;
HttpResponseMessage response;
using (var httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri("https://yourApiAdress.com");
//Yours string value.
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("MyStringContent", "someString")
});
//Sending http post request.
response = await httpClient.PostAsync($"rest/of/apiadress/", content);
}
//Here you save your response to Entity:
var contentStream = await response.Content.ReadAsStreamAsync();
//Options to mach yours naming styles.
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = SnakeCaseNamingPolicy.Instance
};
//Here you go. Yours response as an entity:
myEntity = await JsonSerializer.DeserializeAsync<MyEntity>(contentStream, options);
Snake case naming policy:
using Newtonsoft.Json.Serialization; //For SnakeCaseNamingPolicy.
public class SnakeCaseNamingPolicy : JsonNamingPolicy
{
private readonly SnakeCaseNamingStrategy _newtonsoftSnakeCaseNamingStrategy
= new SnakeCaseNamingStrategy();
public static SnakeCaseNamingPolicy Instance { get; } = new SnakeCaseNamingPolicy();
public override string ConvertName(string name)
{
return _newtonsoftSnakeCaseNamingStrategy.GetPropertyName(name, false);
}
}
If yours another API JSON response looks like:
{
"some_object" : "someValue",
}
Then your entity should look like:
public class MyEntity
{
public object SomeObject { get; set;}
}
CodePudding user response:
This shows you how to send a HttpPost request in .NET. https://zetcode.com/csharp/httpclient/