包括JSON作为HttpPost的一部分,有附件

本文关键字:一部分 JSON 作为 HttpPost 包括 | 更新日期: 2023-09-27 18:12:54

我正在接受一个文件与我的控制器:

[HttpPost, Route("api/upload")]
public async Task<IHttpActionResult> Upload()
{
    if (!Request.Content.IsMimeMultipartContent())
        throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); 
    var provider = new MultipartMemoryStreamProvider();
    await Request.Content.ReadAsMultipartAsync(provider);
    foreach (var file in provider.Contents)
    {
        var filename = file.Headers.ContentDisposition.FileName.Trim(''"');
        var buffer = await file.ReadAsByteArrayAsync();
        //Do whatever you want with filename and its binaray data.
    }
    return Ok();
}

我如何允许客户端也能够在请求的正文中发布json ?

包括JSON作为HttpPost的一部分,有附件

 [Route("{lang}/documents")]
    public async Task PostDocument()
    {
        string dirPath = _appConfigurationManager.GetDocumentFolder();
        if (!Directory.Exists(dirPath))
        {
            DirectoryInfo createdir = Directory.CreateDirectory(dirPath);
        }
        if (Request.Content.IsMimeMultipartContent())
        {
            if (Request.Content.ReadAsStringAsync().Result.ToString().IndexOf("filename='"'"") == -1)
            {
                var streamProvider = new CustomMultipartFormDataStreamProvider(dirPath);
                var result = await Request.Content.ReadAsMultipartAsync(streamProvider);
                var fileEntity = new ViewModels.Common.FileDescViewModel();
                foreach (var file in result.FileData)
                {
                    fileEntity.FileName = file.Headers.ContentDisposition.FileName.Replace("'"", string.Empty);
                    fileEntity.Url = "~/" + fileEntity.FileName;                       
                }
                var jsonmodel = result.FormData["jsonData"].ToString().Replace("'"content'":'"'",", string.Empty);
                if (jsonmodel == null)
                    throw new Exception();
                var siteViewModel = JsonConvert.DeserializeObject<DocumentViewModel>(jsonmodel);
                siteViewModel.Url = fileEntity.Url;                   
                siteViewModel.Name = fileEntity.FileName;
                AddDocumentDetails(siteViewModel);
            }
            else
            {
                string jsonData = Request.Content.ReadAsStringAsync().Result.Replace("'"content'":'"'",", string.Empty);
                jsonData = jsonData.Substring(jsonData.IndexOf('{'), jsonData.LastIndexOf('}') - jsonData.IndexOf('{') + 1);
                var siteViewModel = JsonConvert.DeserializeObject<DocumentViewModel>(jsonData);
                AddDocumentDetails(siteViewModel);
            }
        }
    }

这是我实际的测试代码。