c# - 使用动态对象调用 Web Api 2 和 HttpClient

标签 c# .net asp.net-web-api .net-4.0

我目前正在开发 .NET Framework 4.7.2 应用程序。我需要从我的 C# 代码中调用 Web API Controller 。

我正在更新动态对象,我无法创建任何 View 模型。动态对象具有以下结构,并将动态填充不同的键:

List<KeyValuePair<int,Dictionary<string, object>>>

调用代码如下所示:

var task = Task.Run(async () => await UpdateMyInformation(myDynamicObject));
var test = task.Result;

方法实现:

private async Task<dynamic> UpdateMyInformation(dynamic data)
{
    var content = new StringContent(JsonConvert.SerializeObject(data).ToString(), 
        Encoding.UTF8, "application/json");
    var baseUrl = "http://localhost:1234/api/MyInformationController";

    using (HttpClient client = new HttpClient())
    {
        var response = await client.PutAsync(baseUrl, content);
        response.EnsureSuccessStatusCode();
        var result = response.Content.ReadAsStringAsync().Result;
        return result;
    }

}

API Controller 看起来像这样:

public class MyInformationController : ApiController
{
    [HttpPut]
    public async Task<dynamic> Put(dynamic myData)
    {
       // I need to parse data and return the new dynamic object
       // Manipulate myData according to a given logic

        return myData;
    }
}

我可以在我的 Controller 操作中接收数据,我的问题是:我应该使用动态将 JSON 对象获取到我的 Controller 中吗?

什么可能是解决此问题的更好方法?

最佳答案

我会使用 JObject 而不是动态的。

public class MyInformationController : ApiController
{
    [HttpPut]
    public async Task<dynamic> Put(JObject myData)
    {
       // I need to parse data and return the new dynamic object
       // Manipulate myData according to a given logic

        return myData;
    }
}

通过使用JObject,您可以根据键访问对象中的属性。请参阅docs了解更多信息

关于c# - 使用动态对象调用 Web Api 2 和 HttpClient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52718961/

相关文章:

c# - ListBox 鼠标悬停时的 ListBoxItem 索引

c# - ASP.net 从文件创建一个 Torrent

c# - 共享 1 个网站和 1 个 Web API 的 Azure 应用服务

c# - 使用 ASP.NET Web API 将 yyyy-MM-dd 形式的日期查询参数反序列化为 noda time LocalDate 对象

C# MVC - 根据模型动态获取属性名称

c# - 使用C#的html解析问题

c# - 可以使用 plinq ForAll 批量插入数据库吗?

c# - 如何在 SQL 中检索给定 StoredProcedure 参数的 .NET 类型?

c# - 无法读取流 (StreamReader .net),使用 Angular (1.5) $http.post 和 json 作为数据从 Internet Explorer 10 发送

javascript - 获取下拉菜单的 Angular 值