包含JSON作为具有附件的HttpPost的一部分

时间:2016-10-13 19:55:18

标签: c# asp.net .net json http

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

[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?

1 个答案:

答案 0 :(得分:1)

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

这是我的实际测试代码。尝试它肯定会运行。