简体   繁体   English

如何通过Web API中的post请求接收流和对象?

[英]How to receive stream and object through post request in Web API?

I'm currently developing a REST web service using Web API. 我目前正在使用Web API开发REST Web服务。

Now I am trying to receive stream file and object through the post. 现在我试图通过帖子接收流文件和对象。

When I sent it without the JobPosition object I received the file correctly, also when I sent the JobPosition without the file I received the JobPosition correctly. 当我在没有JobPosition对象的情况下发送它时,我正确地收到了文件,当我在没有文件的情况下发送JobPosition时,我正确地收到了JobPosition。

But when I sent the stream file and the object through the postman I receive the error. 但是当我通过邮递员发送流文件和对象时,我收到错误。

I would appreciate your help to understand if this is possible, and if so, the direction that will help me. 我很感激你的帮助,以了解这是否可能,如果可能的话,我会帮助我。

public class JobPosition
{
    public int Id { set; get; }
    public string Title { set; get; }
}

[HttpPost]
[Route("Job")]
public async Task<bool> Post(JobPosition job)
{
    var multipartMemoryStreamProvider = new MultipartMemoryStreamProvider();
    await Request.Content.ReadAsMultipartAsync(multipartMemoryStreamProvider, new CancellationToken());
    var stream = await multipartMemoryStreamProvider.Contents[0].ReadAsStreamAsync();
    // implementaion
    return true;
}

Postman request: 邮差要求: 在此输入图像描述 在此输入图像描述

I tried all the possible combinations with the Content-Type with no success. 我尝试了Content-Type的所有可能组合但没有成功。

Remove the (JobPosition job) action function parameter, and instead read that with your own code via the multipartMemoryStreamProvider object. 删除(JobPosition job)动作函数参数,而不是通过multipartMemoryStreamProvider对象使用您自己的代码读取它。

await multipartMemoryStreamProvider.Contents[0].ReadAsStreamAsync(); //Stream
await multipartMemoryStreamProvider.Contents[1].ReadAsStreamAsync(); //JSON

Something like that. 这样的事情。 The order will be important. 订单很重要。 It's best if you instead assume it could come in any order, loop over the Contents collection, and handle according to the name of the variable. 最好是假设它可以以任何顺序出现,遍历Contents集合,并根据变量的名称进行处理。

If you are using .NET core, can you try this? 如果您使用的是.NET核心,可以尝试一下吗?

public class JobPosition
{
    public int Id { set; get; }
    public string Title { set; get; }
    public IFormFile jobFile {set; get; }
}

[HttpPost]
[Route("Job")]
public async Task<bool> Post(JobPosition job)
{
    if (!Request.ContentType.Contains("multipart/form-data"))
    {
        return BadRequest();
    }

    // your implementation
    // you can access the file by job.jobFile
    // you can read the contents of the file by opening a read stream from the file object and read it to a byte[]
    return true;
}

More on IFormFile here. 更多关于IFormFile的信息。

Maybe you can use the FormData provided by the MultipartFormDataStreamProvider to extract the JobPosition. 也许您可以使用MultipartFormDataStreamProvider提供的FormData来提取JobPosition。

    public async Task<IHttpActionResult> PostUploadFile()
    {
        // Check if the request contains multipart/form-data.
        if (!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

        string root = HttpContext.Current.Server.MapPath("~/App_Data");
        var provider = new MultipartFormDataStreamProvider(root);

        try
        {
            // Read the form data.
            await Request.Content.ReadAsMultipartAsync(provider);

            NameValueCollection formdata = provider.FormData;

            JobPosition jobPosition = new JobPosition()
            {
                Id = formdata["Id"],
                Title = bool.Parse(formdata["Title"])
            };

            foreach (MultipartFileData file in provider.FileData)
            {
                var fileName = file.Headers.ContentDisposition.FileName.Replace("\"", string.Empty);
                byte[] documentData = File.ReadAllBytes(file.LocalFileName);


                /// Save document documentData to DB or where ever
                /// --- TODO
            }
            return Ok(jobPosition);
        }
        catch (System.Exception e)
        {
            return BadRequest(e.Message);
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM