【问题标题】:Testing ASP.NET Web API Multipart Form Data File upload测试 ASP.NET Web API 多部分表单数据文件上传
【发布时间】:2013-07-18 14:10:58
【问题描述】:

我正在尝试使用 N-UNIT 来测试我的 Web API 应用程序,但我找不到合适的方法来测试我的文件上传方法。哪种方法是测试该方法的最佳方法?

Web API 控制器:

[AcceptVerbs("post")]
public async Task<HttpResponseMessage> Validate()
    {
        // Check if the request contains multipart/form-data.
        if (!Request.Content.IsMimeMultipartContent())
        {
            return Request.CreateErrorResponse(HttpStatusCode.UnsupportedMediaType,"please submit a valid request");
        }
        var provider = new MultipartMemoryStreamProvider(); // this loads the file into memory for later on processing 
        try
        {
            await Request.Content.ReadAsMultipartAsync(provider);
            var resp = new HttpResponseMessage(HttpStatusCode.OK);
            foreach (var item in provider.Contents)
            {
                if (item.Headers.ContentDisposition.FileName != null)
                {
                    Stream stream = item.ReadAsStreamAsync().Result;
        // do some stuff and return response
                    resp.Content = new StringContent(result, Encoding.UTF8, "application/xml"); //text/plain "application/xml"
                    return resp;
                }
            }
               return resp;
        }
        catch (System.Exception e)
        {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
        }
    }

【问题讨论】:

    标签: unit-testing asp.net-web-api nunit http-post


    【解决方案1】:

    根据您的上述评论,以下是一个示例:

    HttpClient client = new HttpClient();
    
    MultipartFormDataContent formDataContent = new MultipartFormDataContent();
    formDataContent.Add(new StringContent("Hello World!"),name: "greeting");
    StreamContent file1 = new StreamContent(File.OpenRead(@"C:\Images\Image1.jpeg"));
    file1.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
    file1.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
    file1.Headers.ContentDisposition.FileName = "Image1.jpeg";
    formDataContent.Add(file1);
    StreamContent file2 = new StreamContent(File.OpenRead(@"C:\Images\Image2.jpeg"));
    file2.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
    file2.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
    file2.Headers.ContentDisposition.FileName = "Image1.jpeg";
    formDataContent.Add(file2);
    
    HttpResponseMessage response = client.PostAsync("http://loclhost:9095/api/fileuploads", formDataContent).Result;
    

    网络上的请求是这样的:

    POST http://localhost:9095/api/fileuploads HTTP/1.1
    Content-Type: multipart/form-data; boundary="34d56c28-919b-42ab-8462-076b400bd03f"
    Host: localhost:9095
    Content-Length: 486
    Expect: 100-continue
    Connection: Keep-Alive
    
    --34d56c28-919b-42ab-8462-076b400bd03f
    Content-Type: text/plain; charset=utf-8
    Content-Disposition: form-data; name=greeting
    
    Hello World!
    --34d56c28-919b-42ab-8462-076b400bd03f
    Content-Type: image/jpeg
    Content-Disposition: form-data; filename=Image1.jpeg
    
    ----Your Image here-------
    --34d56c28-919b-42ab-8462-076b400bd03f
    Content-Type: image/jpeg
    Content-Disposition: form-data; filename=Image2.jpeg
    
    ----Your Image here-------
    --34d56c28-919b-42ab-8462-076b400bd03f--
    

    【讨论】:

    • 我一直在寻找一个简单的解决方案,这会使很多事情复杂化
    【解决方案2】:

    在花了一些时间研究 WebClient 之后,我想出了这个:

         try
            {
                var imageFile = Path.Combine("dir", "fileName");
                WebClient webClient = new WebClient();
                byte[] rawResponse = webClient.UploadFile(string.Format("{0}/api/values/", "http://localhost:12345/"), imageFile);
                Console.WriteLine("Sever Response: {0}", System.Text.Encoding.ASCII.GetString(rawResponse)); // for debugging purposes
                Console.WriteLine("File Upload was successful"); 
            }
            catch (WebException wexc)
            {
               Console.WriteLine("Failed with an exception of " + wexc.Message);  
               // anything other than 200 will trigger the WebException
    
            }
    

    【讨论】:

    • 为什么不使用 System.Net.Http 中的 HttpClient?
    • 我认为HttpClient没有专门为文件上传设计的上传文件。
    猜你喜欢
    • 2017-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多