c# web api 2 通过字典上传端点

c# web api 2 pass dictionary to upload endpoint

目前我有这个端点:

    [HttpPost]
    [Route("{containerName}/{reference}")]
    [ResponseType(typeof(Document))]
    [ClaimsAuthorization(ClaimName = "Administrator")]
    public async Task<IHttpActionResult> CreateAsync(string containerName, string reference) => Ok(await _provider.CreateAsync(Request, containerName, reference));

如您所见,它有一些参数是我的上传控制器的 path 的一部分。我想向此方法发送 Dictionary<string, string>。可能吗?

出于说明目的,这就是我尝试调用端点的方式:

function save(containerName, reference, file, metadata, onComplete) {
    var message;
    if (!containerName) message = 'You must supply a container name.';
    if (!reference) message ='You must supply a reference.';
    if (!file) message = 'No file was provided.';
    if (message) { 
        ngNotify.set(message, { type: 'warn' });
        return $q.reject(message);
    }

    var url = apiUrl + 'documents/' + containerName + '/' + reference;
    var formData = new FormData();            
    var request = {
        method: 'POST',
        url: url,
        data: formData,
        headers: {
            'Content-Type': undefined
        }
    };

    formData.append('file', file);
    formData.append('metadata', metadata);

    return $http(request).then(function (response) {
        SimpleCache.remove(apiUrl + '/documents');
        listDirectiveService.refresh('file');
        ngNotify.set('Your document was created.');
    }, notifications.handleError).finally(function () {                
        onComplete();
    });
}

是的,可以将字典发送到此方法。可以在表单正文或查询字符串中发送数据,但在表单正文中发送可以避免 URL 编码问题和 URL 长度限制。

要查看字典在 JSON 时的样子,请将字典序列化为 JSON。例如:

var dictionary = {
  "Item 1": "Value 1",
  "Item 2": "Value 2",
  "Item 3": "Value 3"
}
formData.append('dictionary', JSON.stringify(dictionary));

您可以使用 FromBody 注释来定义应在请求正文中传递的 属性:

[HttpPost]
[Route("{containerName}/{reference}")]
[ResponseType(typeof(Document))]
[ClaimsAuthorization(ClaimName = "Administrator")]
public async Task<IHttpActionResult> CreateAsync(string containerName, string reference, [FromBody] Dictionary<string,string> myDictionary)