简体   繁体   English

在属性路由中使用字典作为输入参数

[英]Using a Dictionary as input parameter on Attribute Routing

I have the following RESTful Action on an MVC-project: 我在MVC项目上具有以下RESTful Action:

[Route("save")]
[HttpPut]
public ActionResult UpdateAllSettings(Dictionary<string,object> values){}

Currently I am stuck sending values to that Action. 目前,我一直在向该操作发送值。 I tried using the following JSON-Structure: 我尝试使用以下JSON结构:

fancyData="'values':[{'key':'k1','value':'v1'}]";
$http({url:'myurl',data: fancyData}

but values is always null. 但是值始终为null。

I also tried replacing Dictionary<string,object> by List<KeyValuePair<string,object>> with the same results 我还尝试用相同的结果将List<KeyValuePair<string,object>>替换为Dictionary<string,object>

您必须告诉操作以在请求正文中查找数据:

public ActionResult UpdateAllSettings([FromBody]Dictionary<string,object> values){}

In this case it would be better that you decorate the values parameter with the FromBody attribute. 在这种情况下,最好使用FromBody属性装饰values参数。 This gives you the benefit that when creating the PUT request you can add the JSON -content as content to the request. 这给您带来的好处是,在创建PUT请求时,您可以将JSON -content作为内容添加到请求中。

httpClient.PutAsync("URL", new StringContent("YOUR JSON HERE",
                                             Encoding.UTF8,
                                             "application/json"));

To have better reusability just derive from StringContent and create a JSONContent-class: 为了具有更好的可重用性,只需从StringContent派生并创建一个JSONContent-class:

public sealed class JsonContent : StringContent
{
    public JsonContent(object content)
        : base(JsonConvert.SerializeObject(content))
    {
    }

    public JsonContent(object content, Encoding encoding)
        : base(JsonConvert.SerializeObject(content), encoding, "application/json")
    {
    }
}

Note I use Json.NET as JSON library 注意我使用Json.NET作为JSON库

now you can modify it to: 现在您可以将其修改为:

httpClient.PutAsync("URL", new JsonContent(yourDictionaryHere,
                                           Encoding.UTF8,
                                           "application/json"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM