Asp.net web api 在方法POST中接收数据和文件

Asp.net web api 在方法POST中接收数据和文件,asp.net-web-api,Asp.net Web Api,我有一个Web服务,它使用POST方法工作并接收文件,但在其中我还需要同时接收数据 ASP.NET WebApi代码: public Task<HttpResponseMessage> Post() { HttpRequestMessage request = this.Request; if (!request.Content.IsMimeMultipartContent()) { throw new

我有一个Web服务,它使用POST方法工作并接收文件,但在其中我还需要同时接收数据

ASP.NET WebApi代码:

public Task<HttpResponseMessage> Post()
    {
        HttpRequestMessage request = this.Request;
        if (!request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

        string root = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/uploads");
        var provider = new MultipartFormDataStreamProvider(root);

        var task = request.Content.ReadAsMultipartAsync(provider).
            ContinueWith<HttpResponseMessage>(o =>
            {
                string file1 = provider.FileData.First().LocalFileName;

                return new HttpResponseMessage()
                {
                    Content = new StringContent("File uploaded.")
                };
            }
        );
        return task;
    }
如何将服务器更改为不仅读取文件,还读取数据

有人能帮忙吗?
提前感谢。

在本例中,客户端android会在主体中发送额外的值,如media\u type\u png。我不得不做一些类似的事情,但客户端是棱角分明的,不是一个移动应用程序,经过一些搜索后,我从下面找到了代码。这导致了下面的代码

首先接收传入的消息并检查您是否可以处理它,即
[IsMimeMultipartContent][1]()

MultipartFormDataMemoryStreamProvider的定义如下:

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web;

namespace YOURNAMESPACE
{
    public class MultipartFormDataMemoryStreamProvider : MultipartMemoryStreamProvider
    {
        private readonly Collection<bool> _isFormData = new Collection<bool>();
        private readonly NameValueCollection _formData = new NameValueCollection(StringComparer.OrdinalIgnoreCase);
        private readonly Dictionary<string, Stream> _fileStreams = new Dictionary<string, Stream>();

        public NameValueCollection FormData
        {
            get { return _formData; }
        }

        public Dictionary<string, Stream> FileStreams
        {
            get { return _fileStreams; }
        }

        public override Stream GetStream(HttpContent parent, HttpContentHeaders headers)
        {
            if (parent == null)
            {
                throw new ArgumentNullException("parent");
            }

            if (headers == null)
            {
                throw new ArgumentNullException("headers");
            }

            var contentDisposition = headers.ContentDisposition;
            if (contentDisposition == null)
            {
                throw new InvalidOperationException("Did not find required 'Content-Disposition' header field in MIME multipart body part.");
            }

            _isFormData.Add(String.IsNullOrEmpty(contentDisposition.FileName));
            return base.GetStream(parent, headers);
        }

        public override async Task ExecutePostProcessingAsync()
        {
            for (var index = 0; index < Contents.Count; index++)
            {
                HttpContent formContent = Contents[index];
                if (_isFormData[index])
                {
                    // Field
                    string formFieldName = UnquoteToken(formContent.Headers.ContentDisposition.Name) ?? string.Empty;
                    string formFieldValue = await formContent.ReadAsStringAsync();
                    FormData.Add(formFieldName, formFieldValue);
                }
                else
                {
                    // File
                    string fileName = UnquoteToken(formContent.Headers.ContentDisposition.FileName);
                    Stream stream = await formContent.ReadAsStreamAsync();
                    FileStreams.Add(fileName, stream);
                }
            }
        }

        private static string UnquoteToken(string token)
        {
            if (string.IsNullOrWhiteSpace(token))
            {
                return token;
            }

            if (token.StartsWith("\"", StringComparison.Ordinal) && token.EndsWith("\"", StringComparison.Ordinal) && token.Length > 1)
            {
                return token.Substring(1, token.Length - 2);
            }

            return token;
        }
    }
}
使用系统;
使用System.Collections.Generic;
使用System.Collections.ObjectModel;
使用System.Collections.Specialized;
使用System.IO;
使用System.Linq;
使用System.Net.Http;
使用System.Net.Http.Header;
使用System.Threading.Tasks;
使用System.Web;
名称空间YOURNAMESPACE
{
公共类MultipartFormDataMemoryStreamProvider:MultipartMemoryStreamProvider
{
私有只读集合_isFormData=new Collection();
私有只读NameValueCollection _formData=新的NameValueCollection(StringComparer.OrdinalIgnoreCase);
专用只读词典_fileStreams=new Dictionary();
public NameValueCollection表单数据
{
获取{return\u formData;}
}
公共字典文件流
{
获取{return\u fileStreams;}
}
公共重写流GetStream(HttpContent父级、HttpContentHeaders头)
{
如果(父项==null)
{
抛出新的ArgumentNullException(“父级”);
}
if(headers==null)
{
抛出新的ArgumentNullException(“头”);
}
var contentDisposition=headers.contentDisposition;
if(contentDisposition==null)
{
抛出新的InvalidOperationException(“在MIME多部分正文部分中未找到所需的“内容处置”标题字段”);
}
_Add(String.IsNullOrEmpty(contentDisposition.FileName));
返回base.GetStream(父级,头);
}
公共覆盖异步任务ExecutePostProcessingAsync()
{
对于(var index=0;index1)
{
返回token.Substring(1,token.Length-2);
}
返回令牌;
}
}
}

这是一个类似的问题,我在下面的回答中添加了一个摘要。只需添加这两行就解决了我的问题:var result=o.result;var myParameter=result.FormData.GetValues(“完整路径”).FirstOrDefault();
[HttpPost] 
public async Task<HttpResponseMessage> Upload()
{
    // Here we just check if we can support this
    if (!Request.Content.IsMimeMultipartContent())
    {
        this.Request.CreateResponse(HttpStatusCode.UnsupportedMediaType);
    }

    // This is where we unpack the values
    var provider = new MultipartFormDataMemoryStreamProvider();
    var result = await Request.Content.ReadAsMultipartAsync(provider);

    // From the form data we can extract any additional information Here the DTO is any object you want to define
    AttachmentInformationDto attachmentInformation = (AttachmentInformationDto)GetFormData(result);
    // For each file uploaded
    foreach (KeyValuePair<string, Stream> file in provider.FileStreams)
    {
        string fileName = file.Key;
        // Read the data from the file
        byte[] data = ReadFully(file.Value);
        // Save the file or do something with it
    }
}
 // Extracts Request FormatData as a strongly typed model
private object GetFormData(MultipartFormDataMemoryStreamProvider result)
{
    if (result.FormData.HasKeys())
    {
        // Here you can read the keys sent in ie
        result.FormData["your key"]
        AttachmentInformationDto data = AttachmentInformationDto();
        data.ContentType = Uri.UnescapeDataString(result.FormData["ContentType"]); // Additional Keys
        data.Description = Uri.UnescapeDataString(result.FormData["Description"]); // Another example
        data.Name = Uri.UnescapeDataString(result.FormData["Name"]); // Another example
        if (result.FormData["attType"] != null)
        {
            data.AttachmentType = Uri.UnescapeDataString(result.FormData["attType"]);
        }
        return data;
    }

    return null;
}
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web;

namespace YOURNAMESPACE
{
    public class MultipartFormDataMemoryStreamProvider : MultipartMemoryStreamProvider
    {
        private readonly Collection<bool> _isFormData = new Collection<bool>();
        private readonly NameValueCollection _formData = new NameValueCollection(StringComparer.OrdinalIgnoreCase);
        private readonly Dictionary<string, Stream> _fileStreams = new Dictionary<string, Stream>();

        public NameValueCollection FormData
        {
            get { return _formData; }
        }

        public Dictionary<string, Stream> FileStreams
        {
            get { return _fileStreams; }
        }

        public override Stream GetStream(HttpContent parent, HttpContentHeaders headers)
        {
            if (parent == null)
            {
                throw new ArgumentNullException("parent");
            }

            if (headers == null)
            {
                throw new ArgumentNullException("headers");
            }

            var contentDisposition = headers.ContentDisposition;
            if (contentDisposition == null)
            {
                throw new InvalidOperationException("Did not find required 'Content-Disposition' header field in MIME multipart body part.");
            }

            _isFormData.Add(String.IsNullOrEmpty(contentDisposition.FileName));
            return base.GetStream(parent, headers);
        }

        public override async Task ExecutePostProcessingAsync()
        {
            for (var index = 0; index < Contents.Count; index++)
            {
                HttpContent formContent = Contents[index];
                if (_isFormData[index])
                {
                    // Field
                    string formFieldName = UnquoteToken(formContent.Headers.ContentDisposition.Name) ?? string.Empty;
                    string formFieldValue = await formContent.ReadAsStringAsync();
                    FormData.Add(formFieldName, formFieldValue);
                }
                else
                {
                    // File
                    string fileName = UnquoteToken(formContent.Headers.ContentDisposition.FileName);
                    Stream stream = await formContent.ReadAsStreamAsync();
                    FileStreams.Add(fileName, stream);
                }
            }
        }

        private static string UnquoteToken(string token)
        {
            if (string.IsNullOrWhiteSpace(token))
            {
                return token;
            }

            if (token.StartsWith("\"", StringComparison.Ordinal) && token.EndsWith("\"", StringComparison.Ordinal) && token.Length > 1)
            {
                return token.Substring(1, token.Length - 2);
            }

            return token;
        }
    }
}