asp.net C#多部分响应构建

gmxoilav  于 2023-04-22  发布在  .NET
关注(0)|答案(2)|浏览(106)

我给处理程序编了码:

using System;
using System.Net;
using System.Web;

namespace Teste
{
    public class Exemplo : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.Clear();
            context.Response.StatusCode = (int)HttpStatusCode.OK;

            string boundary = CreateFormDataBoundary();
            context.Response.ContentType = "multipart/form-data; boundary=" + boundary;
            //context.Response.ContentType = "plain/text";
            context.Response.ContentEncoding = System.Text.Encoding.UTF8;

            context.Response.Headers.Add("X-data", "21-08-2017");
            context.Response.Headers.Add("X-numberfiles", "2");
            context.Response.Headers.Add("X-Id", "45625625EFA22AD");

            string[] files = new string[] { @"C:\Exemplo\Ficheiros\Fich1.txt", @"C:\Exemplo\Ficheiros\Fich2.txt" };

            string result = "";
            foreach (string f in files)
            {
                result = result + WriteFilePart(boundary, f);
            }
            result = result + Environment.NewLine + "--" + boundary;
            context.Response.Write(result);
        }
        private string CreateFormDataBoundary()
        {
            return "---------------------------" + DateTime.Now.Ticks.ToString("x");
        }
        private string WriteFilePart(string boundary, string FileName)
        {
            //Write boundary with file multipart header.
            string Tosend = "";
            Tosend = Tosend + Environment.NewLine + "--" + boundary + Environment.NewLine;
            Tosend = Tosend + "Content-Type: " + "text/plain" + "" + Environment.NewLine;
            Tosend = Tosend + "Content-Location: " + FileName + "" + Environment.NewLine;
            Tosend = Tosend + "Content-Disposition: attachment; filename=\"" + FileName + "\"" + Environment.NewLine;
            Tosend = Tosend + "Content-ID: " + FileName + "" + Environment.NewLine;
            Tosend = Tosend + Environment.NewLine;

            Tosend = Tosend + Environment.NewLine;
            var reader = new System.IO.StreamReader(FileName);
            var data = reader.ReadToEnd();
            var dataBinary = System.Text.Encoding.UTF8.GetBytes(data);
            Tosend = Tosend + System.Text.Encoding.UTF8.GetString(dataBinary);
            Tosend = Tosend + Environment.NewLine;

            return Tosend;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

如果我使用context.Response.ContentType = "multipart/form-data; boundary=" + boundary;,这是应该发生的事情,我会得到fiddler响应(fiddler说没有响应体):

HTTP/1.1 200 OK
Cache-Control: private
Content-Type: multipart/form-data; boundary=---------------------------8d5bf0fdc7ec8f6; charset=utf-8
Server: Microsoft-IIS/10.0
X-data: 21-08-2017
X-numberfiles: 2
X-Id: 45625625EFA22AD
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?QzpcQ2VydGlmaWNhw6fDo29TQVBcQ2VydGlmaWNhY2FvU0FQX3YxXFNBUENlcnRcVGVzdGUxXEV4ZW1wbG8uYXNoeA==?=
X-Powered-By: ASP.NET
Date: Mon, 21 May 2018 10:41:58 GMT
Content-Length: 581

如果我使用context.Response.ContentType = "plain/text",我会得到fiddler响应,它将期望接收multipart:

HTTP/1.1 200 OK
Cache-Control: private
Content-Type: plain/text; charset=utf-8
Server: Microsoft-IIS/10.0
X-data: 21-08-2017
X-numberfiles: 2
X-Id: 45625625EFA22AD
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?QzpcQ2VydGlmaWNhw6fDo29TQVBcQ2VydGlmaWNhY2FvU0FQX3YxXFNBUENlcnRcVGVzdGUxXEV4ZW1wbG8uYXNoeA==?=
X-Powered-By: ASP.NET
Date: Mon, 21 May 2018 10:40:37 GMT
Content-Length: 581

-----------------------------8d5bf0fac25e36f
Content-Type: text/plain
Content-Location: C:\Exemplo\Ficheiros\Fich1.txt
Content-Disposition: attachment; filename="C:\Exemplo\Ficheiros\Fich1.txt"
Content-ID: C:\Exemplo\Ficheiros\Fich1.txt

Nome:joao
Idade:53

-----------------------------8d5bf0fac25e36f
Content-Type: text/plain
Content-Location: C:\Exemplo\Ficheiros\Fich2.txt
Content-Disposition: attachment; filename="C:\Exemplo\Ficheiros\Fich2.txt"
Content-ID: C:\Exemplo\Ficheiros\Fich2.txt

Dados Adicionais

-----------------------------8d5bf0fac25e36f

说明书上明明写着响应应该是multipart/form-data,为什么我用multipart/form-data得到的不是body,最后的结果应该是用plain/text得到的响应,而用context.Response.ContentType = "multipart/form-data;得到的,我到底做错了什么?
Tkx
当我尝试使用System.Net.Http.MultipartFormDataContent作为context.Response.Write(result);中的内容时,fiddler显示System.Net.Http.MultipartFormDataContent作为主体
根据Liam的建议,更改了以下代码:

public void ProcessRequest(HttpContext context)
    {
        context.Response.Clear();
        context.Response.StatusCode = (int)HttpStatusCode.OK;

        string boundary = CreateFormDataBoundary();
        context.Response.ContentType = "multipart/mixed; boundary=" + boundary;
        //context.Response.ContentType = "plain/text";
        context.Response.ContentEncoding = System.Text.Encoding.UTF8;

        context.Response.Headers.Add("X-data", "21-08-2017");
        context.Response.Headers.Add("X-numberfiles", "2");
        context.Response.Headers.Add("X-Id", "45625625EFA22AD");

        string[] files = new string[] { @"C:\Exemplo\Ficheiros\Fich1.txt", @"C:\Exemplo\Ficheiros\Fich2.txt" };

        //string result = "";
        //foreach (string f in files)
        //{
        //    result = result + WriteFilePart(boundary, f);
        //}
        //result = result + Environment.NewLine + "--" + boundary;
        //StringContent a = (result);

        //HttpContent stringContent = new StringContent(result);
        ProcessRequestM(context);
        //context.Response.Write();
    }
    public void ProcessRequestM(HttpContext context)
    {
        Stream fileStream1 = File.OpenRead(@"C:\Exemplo\Ficheiros\Fich1.txt");
        Stream fileStream2 = File.OpenRead(@"C:\Exemplo\Ficheiros\Fich2.txt");

        HttpContent stringContent = new StringContent("parametro");
        HttpContent fileStreamContent1 = new StreamContent(fileStream1);
        HttpContent fileStreamContent2 = new StreamContent(fileStream2);
        //HttpContent bytesContent = new ByteArrayContent(paramFileBytes);
        using (var client = new HttpClient())
        using (var formData = new MultipartFormDataContent())
        {
            formData.Add(stringContent, "param1", "param1");
            formData.Add(fileStreamContent1, "file1", "file1");
            formData.Add(stringContent, "param2", "param2");
            formData.Add(stringContent, "param2", "param2");
            formData.Add(fileStreamContent2, "file2", "file2");
            context.Response.Write(formData);
        }
    }

Fiddler回应:

HTTP/1.1 200 OK
Cache-Control: private
Content-Type: multipart/mixed; boundary=---------------------------8d5bf354c77d23a; charset=utf-8
Server: Microsoft-IIS/10.0
X-data: 21-08-2017
X-numberfiles: 2
X-Id: 45625625EFA22AD
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?QzpcQ2VydGlmaWNhw6fDo29TQVBcQ2VydGlmaWNhY2FvU0FQX3YxXFNBUENlcnRcVGVzdGUxXEV4ZW1wbG8uYXNoeA==?=
X-Powered-By: ASP.NET
Date: Mon, 21 May 2018 15:09:57 GMT
Content-Length: 40

System.Net.Http.MultipartFormDataContent

越来越绝望

r6hnlfcb

r6hnlfcb1#

我无法解释的是,我是服务器。我只看到请求,我不创建它,所以建议的方法不适用。我是如何做到的:

public resp(HttpContext context)
    {
        context.Response.Clear();
        context.Response.StatusCode = (int)HttpStatusCode.OK;

        string formDataBoundary = String.Format("----------{0:N}", DateTime.Now.Ticks.ToString("x"));
        context.Response.ContentType = "multipart/form-data; boundary=" + formDataBoundary;
        context.Response.ContentEncoding = System.Text.Encoding.UTF8;

        context.Response.Headers.Add("X-data", "21-08-2017");
        context.Response.Headers.Add("X-numberfiles", "2");
        context.Response.Headers.Add("X-Id", "45625625EFA22AD");

        string[] files = new string[] { @"C:\Exemplo\Ficheiros\Fich1.txt", @"C:\Exemplo\Ficheiros\Fich2.txt" };
        Stream memStream = new MemoryStream();
        var boundarybytes = System.Text.Encoding.UTF8.GetBytes("--" + formDataBoundary + "\r\n");
        var endBoundaryBytes = System.Text.Encoding.UTF8.GetBytes("\r\n--" + formDataBoundary + "--");

        foreach (var FileName in files)
        {
            WriteFilePart(context, FileName, boundarybytes, memStream);
            boundarybytes = System.Text.Encoding.UTF8.GetBytes("\r\n--" + formDataBoundary + "\r\n");
        }

        memStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);

        using (Stream ResponseStream = context.Response.OutputStream)
        {
            memStream.Position = 0;
            byte[] tempBuffer = new byte[memStream.Length];
            memStream.Read(tempBuffer, 0, tempBuffer.Length);
            memStream.Close();
            ResponseStream.Write(tempBuffer, 0, tempBuffer.Length);
        }

    }
    private string WriteFilePart(HttpContext context, string FileName, byte[] boundarybytes, Stream memStream)
        {

            string Tosend = "";
            Tosend = Tosend + "Content-Type: " + "text/plain" + "" + Environment.NewLine;
            Tosend = Tosend + "Content-Location: " + FileName + "" + Environment.NewLine;
            Tosend = Tosend + "Content-Disposition: attachment; filename=\"" + FileName + "\"" + Environment.NewLine;
            Tosend = Tosend + "Content-ID: " + FileName + "" + Environment.NewLine;
            Tosend = Tosend + Environment.NewLine;

            memStream.Write(boundarybytes, 0, boundarybytes.Length);
            var headerbytes = System.Text.Encoding.UTF8.GetBytes(Tosend);
            memStream.Write(headerbytes, 0, headerbytes.Length);

            var filebyte = MultipartParser.Parse.FileToByteArray(FileName);  //converts file to byte[]
            memStream.Write(filebyte, 0, filebyte.Length);

        }
iaqfqrcu

iaqfqrcu2#

public async Task SendMultiPart()
    {
        string formDataBoundary = String.Format("----------{0:N}", DateTime.Now.Ticks.ToString("x"));
        HttpContext.Response.ContentType = "multipart/form-data; boundary=" + formDataBoundary;

        var mp = GetMultipart(formDataBoundary);
        await mp.CopyToAsync(HttpContext.Response.Body);
    }

    public MultipartFormDataContent GetMultipart(string formDataBoundary)
    {
        var file_bytes = System.IO.File.ReadAllBytes(Path.Combine("files", "file.txt"));

        var formData = new MultipartFormDataContent(formDataBoundary);
        formData.Add(new StringContent("Ahalay"), "username");
        formData.Add(new ByteArrayContent(file_bytes, 0, file_bytes.Length), "profile_pic", "free.png");
        return formData;
    }

相关问题