ASP .Net网络表单Web API - 如果文件附加FORMDATA是空的 [英] ASP Net Web Form Web API - FormData is empty if file is attached

查看:142
本文介绍了ASP .Net网络表单Web API - 如果文件附加FORMDATA是空的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用ASP.NET的Web表单4.5.1和Asp网网页API,我试图发送一些数据和文件与Web API方法,
我的code基于<$c$c>[http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-2][1]
但我想通过AJAX发送数据(jQuery的)

  VAR FORMDATA =新FORMDATA();
                变种opmlFile = $('#打包文件')[0​​];
                formData.append(opmlFile,opmlFile.files [0]);
                formData.append(packageData,JSON.stringify(ko.mapping.toJS(this.selectedItem)));                $阿贾克斯({
                    键入:POST,
                    网址:/ API / myController的/的MyMethod
                    数据类型:JSON
                    数据:FORMDATA,
                    缓存:假的,
                    的contentType:假的,
                    过程数据:假的,
                    成功:函数(响应){                    },
                    故障:功能(响应){                    }
                });

这似乎是工作的情况下,但如果我在发送请求文件,我的目标数据不可用(provider.FormData.AllKeys)。如何使它运作?当然,我可以送2请求,但它似乎对我不好。

 公共异步任务&LT; Htt的presponseMessage&GT;的MyMethod()
    {
        //检查请求包含的multipart / form-data的。
        如果(!Request.Content.IsMimeMultipartContent())
        {
            抛出新的Htt presponseException(的HTTPStatus code.UnsupportedMediaType);
        }        串根= HttpContext.Current.Server.MapPath(〜/ App_Data文件);
        VAR提供商=新MultipartFormDataStreamProvider(根);        //读取表单数据并返回一个异步任务。
        VAR任务= Request.Content.ReadAsMultipartAsync(供应商)。
            ContinueWith&LT; Htt的presponseMessage&GT;(T =&GT;
            {
                如果(t.IsFaulted || t.IsCanceled)
                {
                    Request.CreateErrorResponse(的HTTPStatus code.InternalServerError,t.Exception);
                }                //这说明如何获取文件名。
                的foreach(在provider.FileData MultipartFileData文件)
                {
                    Trace.WriteLine(file.Headers.ContentDisposition.FileName);
                    Trace.WriteLine(服务器文件路径:+ file.LocalFileName);
                }                的foreach(在provider.FormData.AllKeys VAR键)
                {
                    的foreach(在provider.FormData.GetValues​​ VAR VAL(键))
                    {
                        Trace.WriteLine(的String.Format({0}:{1}键,VAL));
                    }
                }                返回Request.CreateResponse(的HTTPStatus code.OK);
            });        返回等待任务;    }


解决方案

下面的多部分的要求是有JSON +文件数据,其中如 MultipartFormDataStreamProvider 预计表单数据+文件。典型的多部分FORMDATA要求的样子..an例如...注意到称为标题内容处置:表格数据 ...

  POST HTTP://本地主机:50460 / API /价值/ 1 HTTP / 1.1
用户代理:Mozilla的/ 5.0(Windows NT的6.1; WOW64; RV:12.0)的Gecko / 20100101火狐/ 12.0
接受:text / html的,是application / xhtml + xml的,应用/ XML; Q = 0.9 * / *; Q = 0.8
接受语言:EN-US,连接; Q = 0.5
接受编码:gzip,紧缩
内容类型:多重/ form-data的;边界= --------------------------- 41184676334
内容长度:29278----------------------------- 41184676334
内容处置:表格数据; NAME =标题暑假
----------------------------- 41184676334
内容处置:表格数据; NAME =此搜索;文件名=GrandCanyon.jpg
内容类型:图像/ JPEG(未示出二进制数据)
----------------------------- 41184676334--

有关您的情况,您可以创建自定义的多部分流提供从抽象推导 MultipartStreamProvider 或者你可以做这样的事情如下:

 客户客户= NULL;
的foreach(HttpContent在provider.Contents内容)
{
    如果(content.Headers.ContentType.MediaType ==应用/ JSON)
    {
        客户=等待content.ReadAsAsync&LT;客户&GT;();
        打破;
    }
}

I am using Asp net web form 4.5.1 and Asp net web Api and I trying to send some data and file to Web Api method, my code is based on [http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-2][1] example but I want to send data via AJAX (jquery)

var formData = new FormData();
                var opmlFile = $('#packFile')[0];
                formData.append("opmlFile", opmlFile.files[0]);
                formData.append("packageData",  JSON.stringify(ko.mapping.toJS(this.selectedItem)));

                $.ajax({
                    type: "POST",
                    url: "/api/MyController/MyMethod",                   
                    dataType: "json",
                    data: formData,
                    cache: false,
                    contentType: false,
                    processData: false,
                    success: function (response) {

                    },
                    failure: function (response) {

                    }
                });

it seems like working case, but if I send file with in request my object data is not available(provider.FormData.AllKeys ). How to make it works ? of course I can send 2 request but it is seems not good for me.

public async Task<HttpResponseMessage> MyMethod()
    {
        // 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);

        // Read the form data and return an async task.
        var task = Request.Content.ReadAsMultipartAsync(provider).
            ContinueWith<HttpResponseMessage>(t =>
            {
                if (t.IsFaulted || t.IsCanceled)
                {
                    Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
                }

                // This illustrates how to get the file names.
                foreach (MultipartFileData file in provider.FileData)
                {
                    Trace.WriteLine(file.Headers.ContentDisposition.FileName);
                    Trace.WriteLine("Server file path: " + file.LocalFileName);
                }

                foreach (var key in provider.FormData.AllKeys)
                {
                    foreach (var val in provider.FormData.GetValues(key))
                    {
                        Trace.WriteLine(string.Format("{0}: {1}", key, val));
                    }
                }

                return Request.CreateResponse(HttpStatusCode.OK);
            });

        return await task;

    }

解决方案

Here your multipart request is having JSON + file data, where as MultipartFormDataStreamProvider expects form data + file...an example of how a typical multipart formdata request looks like...notice the header called Content-Disposition: form-data...

POST http://localhost:50460/api/values/1 HTTP/1.1
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: multipart/form-data; boundary=---------------------------41184676334
Content-Length: 29278

-----------------------------41184676334
Content-Disposition: form-data; name="caption"

Summer vacation
-----------------------------41184676334
Content-Disposition: form-data; name="image1"; filename="GrandCanyon.jpg"
Content-Type: image/jpeg

(Binary data not shown)
-----------------------------41184676334--

For your scenario, you can either create a custom multipart stream provider deriving from the abstract MultipartStreamProvider or you can do something like below:

Customer customer = null;
foreach(HttpContent content in provider.Contents)
{
    if(content.Headers.ContentType.MediaType == "application/json")
    {
        customer = await content.ReadAsAsync<Customer>();
        break;
    }
}

这篇关于ASP .Net网络表单Web API - 如果文件附加FORMDATA是空的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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