我想向另一个api发送一个包含字符串值的http请求.我想将传入的响应保存为一个实体.

推荐答案

你可以试试这个:

//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);

蛇 case 命名策略:

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);
    }
}

如果您的另一个API JSON响应如下所示:

{
  "some_object" : "someValue",
}

那么您的实体应该看起来像:

public class MyEntity
{
     public object SomeObject { get; set;}
}

.net相关问答推荐

.NET 7.0中的UseHttpsRedirection和IIS生产部署

仅使用 .NET GetBytes 方法转换有效字节而不创建问号

使用 MassTransit、.NET Core 和 RabbitMQ 的设计挑战

查找 2 个已知值之间的字符串

在 .NET 反射中使用 GetProperties() 和 BindingFlags.DeclaredOnly

为什么 .NET 内部 Hashtable 中有一个 Thread.Sleep(1)?

为 XML 编码文本数据的最佳方法

不同命名空间中的部分类

LINQ:确定两个序列是否包含完全相同的元素

Silverlight 与 Flex

我可以从 .NET/C# 获取其他进程的命令行参数吗?

如何在 C# 中打开 Excel 文件?

调用委托与方法的性能

为什么 Interlocked.Exchange 不支持布尔类型?

C#:获得完整的桌面大小?

变量MyException已声明但从未使用

所有数组在 C# 中都实现了哪些接口?

如何在 C# 中以编程方式安装 Windows 服务?

何时何地使用 GetType() 或 typeof()?

嵌套捕获组如何在正则表达式中编号?