c# web api 2传递字典来上传端点

标签 c# multipartform-data

目前我有这个端点:

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

如您所见,其中的一些参数是我的上传 Controller 的路径的一部分。我想发送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));

enter image description here

关于c# web api 2传递字典来上传端点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49778152/

相关文章:

python - 使用 multipart_encode 的问题(海报库)

java - 如何使用多部分/表单数据?

c# - 如何从 List<IEnumerable<ItemClass>> 到 IEnumerable<ItemClass> 进行选择?

c# - 使用 ASP.NET Entity Framework 连接到 MySQL 数据库

c# - MediaTypeFormatter 序列化 web api 中的枚举字符串值

java - 如何在 Android 中使用 WLResourceRequest 创建 Multipart 请求

node.js - 如何使用multer和 typescript 正确处理 Node 发布请求中的req.files

java - 如何处理来自 servlet 的 jsp 响应以进行分段文件上传?

c# - 具有松散类型参数的 WCF OperationContract

c# - WPF IValueConverter - 将多个值转换为单个值