在Asp.Net Core中,如何从主体中获取零件/表单数据? [英] In Asp.Net Core, how can I get the multipart/form-data from the body?

查看:88
本文介绍了在Asp.Net Core中,如何从主体中获取零件/表单数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Asp.Net Core中,似乎他们已经放弃了 Request.Content.ReadAsMultipartAsync 功能,转而使用IFormFile.

In Asp.Net Core, it appears that they have done away with the Request.Content.ReadAsMultipartAsync functionality in favor of the IFormFile.

这使得上载具有实际文件的位置更容易,但是,在我的用例中,我需要将文件上载到浏览器内存,进行处理,然后将其作为多格式数据的一部分发送到身体.IFormFile无法看到此内容,因为没有要读取的实际文件.仅当您在Content-Disposition上具有filename属性并且在客户端上要上传的实际文件时,该方法才有效.

This makes uploading where you have an actual file a LOT easier, however, I have a use case where I need to upload a file to browser memory, process it, then send it as part of the multi-form data in the body. IFormFile cannot see this as there is no actual file to read. It only works if you have a filename property on the Content-Disposition and an actual file on the client to upload.

在我的Asp.Net 4应用程序中,无论是在边界之间发送还是作为附件发送,我都可以读取主体中的mutlipart数据.

In my Asp.Net 4 app, I could read the mutlipart data in the body whether that was sent between boundaries or as an attached file.

如何在.Net Core中完成此操作?

How do I accomplish this in .Net Core?

推荐答案

我发现,多部分值以键/值对数组的形式传递到HttpRequest.Form中.主体的多部分上的名称"值确定键的名称.

What I figured out is that the multipart values are passed into the HttpRequest.Form as an array of key/value pairs. The "name" value on the body's multipart determines the name of the key.

我创建了一个同时获取文件和表单值的帮助程序方法.

I created a helper method that grabs both files and form values.

public static List<FileModel> GetFileModelsFromRequest(HttpRequest request)
{
    var fileModels = new FileModels();

    foreach (var formField in request.Form)
    {
        // Form data 
        var fileModelText = formField.Value;

        ... process and add to the FileModel list
    }

    if (request.Form.Files != null && request.Form.Files.Count > 0)
    {
        foreach (var file in request.Form.Files)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                // File data
                formFile.CopyTo(ms);                    
            }

            ... process and add to the FileModel list
        }
    }

    return fileModels;
}

这篇关于在Asp.Net Core中,如何从主体中获取零件/表单数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆