Skip to main content
 首页 » 编程设计

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

2024年02月04日30小虾米

目前我有这个端点:

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