解析/上侧的WebAPI消耗MultipartFormDataContent(由MVC集) [英] Parsing/Consuming a MultipartFormDataContent (set by MVC) on the WebApi side

查看:136
本文介绍了解析/上侧的WebAPI消耗MultipartFormDataContent(由MVC集)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到了ByteArrayContent工作

  / * MVC方法,ByteArrayContent * /        私人异步任务< Htt的presponseMessage> ExecuteProxy(字符串URL)
        {
            使用(VAR的客户=新的HttpClient(HttpClientHandlerFactory.GetWindowsAuthenticationHttpClientHandler()))
            {                字节[]字节1 =新的字节[] {1,2,3};                ByteArrayContent byteContent =新ByteArrayContent(字节1);                this.Request.Method = HttpMethod.Post;
                this.Request.Content = byteContent;                返回等待client.SendAsync(this.Request);            }
        }/ *的WebAPI委托处理程序,ByteArrayContent * /        保护覆盖任务< Htt的presponseMessage> SendAsync(HTT prequestMessage请求的CancellationToken的CancellationToken)
        {
            VAR的字节数组= request.Content.ReadAsByteArrayAsync()结果。            如果(NULL!=的字节数组)
            {
                / *我看到的1,2,3字节* /
            }
        }

下面的方法是没有问题的一部分,但我有它的完整性。

 公共静态类HttpClientHandlerFactory
{
    公共静态HttpClientHandler GetWindowsAuthenticationHttpClientHandler()
    {
        HttpClientHandler returnHandler =新HttpClientHandler()
        {
            UseDefaultCredentials = TRUE,
            preAuthenticate = TRUE
        };        返回returnHandler;
    }
}

我有麻烦得到的MultipartFormDataContent对事物的一面的WebAPI

  / * MVC方法,MultipartFormDataContent * /        私人异步任务< Htt的presponseMessage> ExecuteProxy(字符串URL)
        {
            使用(VAR的客户=新的HttpClient(HttpClientHandlerFactory.GetWindowsAuthenticationHttpClientHandler()))
            {                字节[]字节1 =新的字节[] {1,2,3};
                ByteArrayContent byteContent1 =新ByteArrayContent(字节1);                的StringContent stringContent1 =新的StringContent(StringContent1Value);                字节[]字节2 =新的字节[] {4,5,6};
                ByteArrayContent byteContent2 =新ByteArrayContent(字节2);                的StringContent stringContent2 =新的StringContent(StringContent2Value);                MultipartFormDataContent multipartContent =新MultipartFormDataContent();
                multipartContent.Add(byteContent1MyByteArrayContent1);
                multipartContent.Add(stringContent1);
                multipartContent.Add(byteContent2MyByteArrayContent2);
                multipartContent.Add(stringContent2);                this.Request.Method = HttpMethod.Post;
                this.Request.Content = multipartContent;                返回等待client.SendAsync(this.Request);            }
        }        / *的WebAPI委托处理程序,MultipartFormDataContent * /        保护覆盖任务< Htt的presponseMessage> SendAsync(HTT prequestMessage请求的CancellationToken的CancellationToken)
        {
            / *我不知道如何改变这一回一个MultipartFormDataContent ..不过还是其他你解析* /
        }

我GOOGLE和阅读它大约40 SOF职位。该解决方案还暗示我。


解决方案

所以魔术方法似乎是ReadAsMultipartAsync

有这个两个问题。一个小一显著。


  1. ReadAsMultipartAsync是一个扩展方法。 (这是小问题)

    / * * System.Net.Http.Formatting.dll /


 使用System.Net.Http.Headers;

这就是为什么我没有在智能感知看到这种方法最初。 (我没有加参考..或using语句到我的.cs)

<醇开始=2>
  • 有与方法本身(在下面的链接所述)
  • 的问题

    <一个href=\"http://stackoverflow.com/questions/15201255/request-content-readasmultipartasync-never-returns\">Request.Content.ReadAsMultipartAsync永远不会返回

    那么下面就是我想出了让按名称的发现。

      / *的WebAPI委托处理程序,MultipartFormDataContent * /    保护覆盖任务&LT; Htt的presponseMessage&GT; SendAsync(HTT prequestMessage请求的CancellationToken的CancellationToken)
        {        / *参见http://stackoverflow.com/questions/15201255/request-content-readasmultipartasync-never-returns * /
            IEnumerable的&LT; HttpContent&GT;内容= NULL;
            Task.Factory.StartNew(
                    ()=&GT;
                    内容= request.Content.ReadAsMultipartAsync()。Result.Contents,
                    CancellationToken.None,
                    TaskCreationOptions.LongRunning,//保证单独的线程
                    TaskScheduler.Default)
                。等待();        如果(NULL!=内容)
            {
                ////这可能与LINQ查询来实现,但我已经离开了for循环中...所以它更容易地看到发生了什么事情
                的foreach(HttpContent currentHttpContent中的内容)
                {
                    如果(NULL!= currentHttpContent)
                    {
                        如果(NULL!= currentHttpContent.Headers)
                        {
                            HttpContentHeaders cheaders = currentHttpContent.Headers;                        如果(NULL!= cheaders)
                            {
                                如果(NULL!= cheaders.ContentDisposition)
                                {
                                    System.Net.Http.Headers.ContentDispositionHeaderValue cdhv = cheaders.ContentDisposition;
                                    如果(NULL!= cdhv)
                                    {
                                        如果(!string.IsNullOrEmpty(cdhv.Name))
                                        {
                                            如果(cdhv.Name.Equals(MyByteArrayContent1,StringComparison.OrdinalIgnoreCase))
                                            {
                                                字节[]的字节数组= NULL;
                                                。//// currentHttpContent.LoadIntoBufferAsync()等待();
                                                ////currentHttpContent.ReadAsByteArrayAsync().ContinueWith(t =&GT;
                                                //// {
                                                ////的字节数组= t.Result;
                                                ////});
                                                的字节数组= currentHttpContent.ReadAsByteArrayAsync()结果。
                                            }                                        / *您还可以检查MyByteArrayContent2,StringContent1Value,StringContent2Value为好,冷落为了简洁* /
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

    其他链接:

    <一个href=\"http://stackoverflow.com/questions/15201255/request-content-readasmultipartasync-never-returns\">Request.Content.ReadAsMultipartAsync永远不会返回

    <一个href=\"http://stackoverflow.com/questions/12384544/multipart-form-post-using-asp-net-web-api\">Multipart使用ASP.Net的Web API 表单POST

    <一个href=\"http://stackoverflow.com/questions/31617663/how-to-get-multipartformdatacontent-in-web-api-post-method\">How在Web.API Post方法来获得MultipartFormDataContent?

    <一个href=\"http://stackoverflow.com/questions/19710812/how-do-i-get-the-file-contents-of-a-multipartmemorystreamprovider-as-a-byte-arra\">How我能得到一个MultipartMemoryStreamProvider的文件内容作为字节数组?

    <一个href=\"http://stackoverflow.com/questions/32184360/post-byte-array-to-web-api-server-using-httpclient\">Post使用字节数组的Web API服务器的HttpClient

    <一个href=\"http://stackoverflow.com/questions/13021089/why-is-the-body-of-a-web-api-request-read-once\">Why读出一次一个Web API请求的主体?

    (无答案下面的一个)

    如何分析MultipartFormDataContent

    附加:

    下面是LINQ查询我想通了:

     如果(空!=内容)
            {
                / *有时ContentDisposition.Name是空,因此额外的过滤器的地方是有帮助的,以避免对象的空引用异常* /
                HttpContent foundContent =(从内容CNT
                                           其中,空= CNT和放大器;!&安培;空= cnt.Headers和放大器;!&安培;空= cnt.Headers.ContentDisposition和放大器;!&安培; !string.IsNullOrEmpty(cnt.Headers.ContentDisposition.Name)及&放大器; cnt.Headers.ContentDisposition.Name.Equals(MyByteArrayContent1,StringComparison.OrdinalIgnoreCase)
                                           选择CNT).FirstOrDefault();            如果(NULL!= foundContent)
                {
                    。字节[]的字节数组= foundContent .ReadAsByteArrayAsync()结果;
                }
            }

    I got the ByteArrayContent to work

    /* MVC Method , ByteArrayContent */
    
            private async Task<HttpResponseMessage> ExecuteProxy(string url)
            {
                using (var client = new HttpClient(HttpClientHandlerFactory.GetWindowsAuthenticationHttpClientHandler()))
                {
    
                    byte[] byte1 = new byte[] { 1, 2, 3 };
    
                    ByteArrayContent byteContent = new ByteArrayContent(byte1);
    
                    this.Request.Method = HttpMethod.Post;
                    this.Request.Content = byteContent;
    
                    return await client.SendAsync(this.Request);                    
    
                }
            }
    
    /* WebApi Delegating Handler , ByteArrayContent */
    
            protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
            {
                var byteArray = request.Content.ReadAsByteArrayAsync().Result;
    
                if (null != byteArray)
                {
                    /* I see the byte of "1,2,3" */
                }
            }
    

    The below method isn't part of the problem, but I include it for completeness.

    public static class HttpClientHandlerFactory
    {
        public static HttpClientHandler GetWindowsAuthenticationHttpClientHandler()
        {
            HttpClientHandler returnHandler = new HttpClientHandler()
            {
                UseDefaultCredentials = true,
                PreAuthenticate = true
            };
    
            return returnHandler;
        }
    }   
    

    I'm having trouble "getting" the MultipartFormDataContent on the WebApi side of things.

    /* MVC Method , MultipartFormDataContent */
    
            private async Task<HttpResponseMessage> ExecuteProxy(string url)
            {
                using (var client = new HttpClient(HttpClientHandlerFactory.GetWindowsAuthenticationHttpClientHandler()))
                {
    
                    byte[] byte1 = new byte[] { 1, 2, 3 };
                    ByteArrayContent byteContent1 = new ByteArrayContent(byte1);
    
                    StringContent stringContent1 = new StringContent("StringContent1Value");
    
                    byte[] byte2 = new byte[] { 4, 5, 6 };
                    ByteArrayContent byteContent2 = new ByteArrayContent(byte2);                
    
                    StringContent stringContent2 = new StringContent("StringContent2Value");
    
                    MultipartFormDataContent multipartContent = new MultipartFormDataContent();
                    multipartContent.Add(byteContent1, "MyByteArrayContent1");
                    multipartContent.Add(stringContent1);   
                    multipartContent.Add(byteContent2, "MyByteArrayContent2");
                    multipartContent.Add(stringContent2);   
    
    
    
                    this.Request.Method = HttpMethod.Post;
                    this.Request.Content = multipartContent;
    
                    return await client.SendAsync(this.Request);                    
    
                }
            }
    
    
    
            /* WebApi Delegating Handler , MultipartFormDataContent*/
    
            protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
            {
                /* I have no idea how to change this back into a MultipartFormDataContent .. or however else you parse it */
            }
    

    I've googled and read about 40 SOF posts about it. The solution still alludes me.

    解决方案

    So the magic method seems to be ReadAsMultipartAsync

    There were two issues with this. One minor, one significant.

    1. ReadAsMultipartAsync is an extension method. (This is the minor issue)

      /* System.Net.Http.Formatting.dll */

    and

    using System.Net.Http.Headers;
    

    This is why I did not see this method originally in the intellisense. (I had not added the reference .. or the using statement to my .cs)

    1. There was an issue with the method itself (outlined in the link below)

    Request.Content.ReadAsMultipartAsync never returns

    So below is what I came up with that allows "by name" finding.

     /* WebApi Delegating Handler , MultipartFormDataContent*/
    
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
    
            /* see http://stackoverflow.com/questions/15201255/request-content-readasmultipartasync-never-returns */
            IEnumerable<HttpContent> contents = null;
            Task.Factory.StartNew(
                    () =>
                    contents = request.Content.ReadAsMultipartAsync().Result.Contents,
                    CancellationToken.None,
                    TaskCreationOptions.LongRunning, // guarantees separate thread
                    TaskScheduler.Default)
                .Wait();
    
            if (null != contents)
            {
                //// This could be accomplished with LINQ queries, but I've left the for-loops in ... so its easier to see what's going on
                foreach (HttpContent currentHttpContent in contents)
                {
                    if (null != currentHttpContent)
                    {
                        if (null != currentHttpContent.Headers)
                        {
                            HttpContentHeaders cheaders = currentHttpContent.Headers;
    
                            if (null != cheaders)
                            {
                                if (null != cheaders.ContentDisposition)
                                {
                                    System.Net.Http.Headers.ContentDispositionHeaderValue cdhv = cheaders.ContentDisposition;
                                    if (null != cdhv)
                                    {
                                        if (!string.IsNullOrEmpty(cdhv.Name))
                                        {
                                            if (cdhv.Name.Equals("MyByteArrayContent1", StringComparison.OrdinalIgnoreCase))
                                            {
                                                byte[] byteArray = null;
                                                ////currentHttpContent.LoadIntoBufferAsync().Wait();
                                                ////currentHttpContent.ReadAsByteArrayAsync().ContinueWith(t =>
                                                ////{
                                                ////    byteArray = t.Result;
                                                ////});
                                                byteArray = currentHttpContent.ReadAsByteArrayAsync().Result;
                                            }
    
                                            /* you can also check for MyByteArrayContent2, StringContent1Value, StringContent2Value as well, left out for brevity */
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    

    Other links:

    Request.Content.ReadAsMultipartAsync never returns

    Multipart form POST using ASP.Net Web API

    How to get MultipartFormDataContent in Web.API Post method?

    How do I get the file contents of a MultipartMemoryStreamProvider as a byte array?

    Post byte array to Web API server using HttpClient

    Why is the body of a Web API request read once?

    (No answer for the below one)

    How to parse MultipartFormDataContent

    APPEND:

    Here is the linq query I figured out:

            if (null != contents)
            {
                /* sometimes the ContentDisposition.Name is null so the extra where filters are helpful to avoid object-null-reference exception */
                HttpContent foundContent = (from cnt in contents
                                           where null!= cnt && null != cnt.Headers && null != cnt.Headers.ContentDisposition && !string.IsNullOrEmpty(cnt.Headers.ContentDisposition.Name) && cnt.Headers.ContentDisposition.Name.Equals("MyByteArrayContent1", StringComparison.OrdinalIgnoreCase)
                                           select cnt).FirstOrDefault();
    
                if (null != foundContent )
                {
                    byte[] byteArray = foundContent .ReadAsByteArrayAsync().Result;
                }
            }
    

    这篇关于解析/上侧的WebAPI消耗MultipartFormDataContent(由MVC集)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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