C# Web API 2:如何向上传端点传递Dictionary<string, string>
如何在你的Web API端点中传递Dictionary<string, string>参数?
我来给你梳理几种适配现有代码的可行方案,你可以根据实际场景选择:
方案1:通过请求体传递(最推荐)
因为你的端点是POST请求,把字典放在请求体里是最规范的做法,也能支持复杂的键值对内容。
只需要修改你的方法签名,添加带[FromBody]特性的字典参数,同时调整你的_provider.CreateAsync方法来接收这个新参数:
[HttpPost] [Route("{containerName}/{reference}")] [ResponseType(typeof(Document))] [ClaimsAuthorization(ClaimName = "Administrator")] public async Task<IHttpActionResult> CreateAsync( string containerName, string reference, [FromBody] Dictionary<string, string> extraData) { return Ok(await _provider.CreateAsync(Request, containerName, reference, extraData)); }
调用这个接口时,请求体要传JSON格式的字典:
{ "customKey1": "customValue1", "customKey2": "customValue2" }
方案2:通过查询字符串传递
如果你的字典参数都是简单的键值对,且不需要保密,也可以把它们放在URL的查询字符串里:
修改方法签名,用[FromUri]特性标记字典参数:
[HttpPost] [Route("{containerName}/{reference}")] [ResponseType(typeof(Document))] [ClaimsAuthorization(ClaimName = "Administrator")] public async Task<IHttpActionResult> CreateAsync( string containerName, string reference, [FromUri] Dictionary<string, string> extraData) { return Ok(await _provider.CreateAsync(Request, containerName, reference, extraData)); }
调用时的URL示例:
POST /api/your-controller-name/your-container/your-reference?customKey1=value1&customKey2=value2
注意:这种方式不适合包含特殊字符或敏感内容的键值对,因为查询字符串会被记录在日志中,且有长度限制。
方案3:适配文件上传场景(结合Request对象)
从你的代码里用到Request来看,这个端点可能是处理文件上传的(比如multipart/form-data请求)。这种情况下,你可以把字典序列化成JSON作为一个表单字段,或者逐个传递键值对:
方式A:读取序列化的JSON表单字段
[HttpPost] [Route("{containerName}/{reference}")] [ResponseType(typeof(Document))] [ClaimsAuthorization(ClaimName = "Administrator")] public async Task<IHttpActionResult> CreateAsync(string containerName, string reference) { // 假设表单中有一个名为"extraData"的字段,值是序列化后的JSON字典 var formData = await Request.Content.ReadAsFormDataAsync(); var extraDataJson = formData["extraData"]; var extraData = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string>>(extraDataJson); return Ok(await _provider.CreateAsync(Request, containerName, reference, extraData)); }
方式B:直接读取所有表单键值对
如果每个字典的键都是独立的表单字段:
[HttpPost] [Route("{containerName}/{reference}")] [ResponseType(typeof(Document))] [ClaimsAuthorization(ClaimName = "Administrator")] public async Task<IHttpActionResult> CreateAsync(string containerName, string reference) { var formData = await Request.Content.ReadAsFormDataAsync(); var extraData = formData.AllKeys.ToDictionary(key => key, key => formData[key]); return Ok(await _provider.CreateAsync(Request, containerName, reference, extraData)); }
不管你选哪种方案,最后都要记得更新你的_provider.CreateAsync方法,让它能接收这个Dictionary<string, string>类型的参数哦。
内容的提问来源于stack exchange,提问作者r3plica
相关产品推荐
相关产品推荐

