微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

asp.net-mvc – 使用Multipart格式的Web API模型绑定

有没有办法能够从ASP.NET MVC Web API中的多部分表单数据请求中获取模型绑定(或任何)来发布模型?

我看到各种博客文章,但事情发生在实际版本和实际版本之间,或者它们不显示模型绑定工作。

这是一个过时的帖子:Sending HTML Form Data

这也是这样的:Asynchronous File Upload using ASP.NET Web API

我发现这个代码(并修改了一些)在某个地方手动读取值:

模型:

public class TestModel
{
    [required]
    public byte[] Stream { get; set; }

    [required]
    public string MimeType { get; set; }
}

控制器:

public HttpResponseMessage Post()
    {
        if (!Request.Content.IsMimeMultipartContent("form-data"))
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

        IEnumerable<HttpContent> parts = Request.Content.ReadAsMultipartAsync().Result.Contents;


        string mimeType;
        if (!parts.TryGetFormFieldValue("mimeType",out mimeType))
        {
            return Request.CreateResponse(HttpStatusCode.BadRequest);
        }

        var media = parts.ToArray()[1].ReadAsByteArrayAsync().Result;

        // create the model here
        var model = new TestModel()
            {
                MimeType = mimeType,Stream = media
            };
        // save the model or do something with it
        // repository.Save(model)

        return Request.CreateResponse(HttpStatusCode.OK);
    }

测试:

[DeploymentItem("test_sound.aac")]
[TestMethod]
public void CanPostMultiPartData()
{
    var content = new MultipartFormDataContent { { new StringContent("audio/aac"),"mimeType"},new ByteArrayContent(File.ReadAllBytes("test_sound.aac")) };

    this.controller.Request = new HttpRequestMessage {Content = content};
    var response = this.controller.Post();

    Assert.AreEqual(response.StatusCode,HttpStatusCode.OK);
}

这个代码基本上是脆弱的,不可维护的,进一步的,不强制模型绑定或数据注释约束。

有没有更好的方法来做到这一点?

更新:我看过这个post,这让我想起来 – 我必须为每个我想支持的模型编写一个新的格式化程序?

解决方法

@Mark琼斯链接到我的博客文章 http://lonetechie.com/2012/09/23/web-api-generic-mediatypeformatter-for-file-upload/,带领我来到这里。我必须考虑如何做你想做的事情。

我相信如果你将我的方法与TryValidateproperty()结合起来,你应该可以完成你所需要的。我的方法会得到反序列化的对象,但是它不会处理任何验证。您需要使用反射来循环遍历对象的属性,然后在每个对象上手动调用TryValidateproperty()。这种方法是多一点手,但我不知道如何做到这一点。

http://msdn.microsoft.com/en-us/library/dd382181.aspx
http://www.codeproject.com/Questions/310997/TryValidateProperty-not-work-with-generic-function

编辑:有人问这个问题,我决定编写代码,以确保它的工作。这是我的博客中更新的验证检查代码

public class FileUpload<T>
{
    private readonly string _RawValue;

    public T Value { get; set; }
    public string FileName { get; set; }
    public string MediaType { get; set; }
    public byte[] Buffer { get; set; }

    public List<ValidationResult> ValidationResults = new List<ValidationResult>(); 

    public FileUpload(byte[] buffer,string mediaType,string fileName,string value)
    {
        Buffer = buffer;
        MediaType = mediaType;
        FileName = fileName.Replace("\"","");
        _RawValue = value;

        Value = JsonConvert.DeserializeObject<T>(_RawValue);

        foreach (PropertyInfo Property in Value.GetType().GetProperties())
        {
            var Results = new List<ValidationResult>();
            Validator.TryValidateProperty(Property.GetValue(Value),new ValidationContext(Value) 
                                          {MemberName = Property.Name},Results);
            ValidationResults.AddRange(Results);
        }
    }

    public void Save(string path,int userId)
    {
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }

        var SafeFileName = Md5Hash.GetSaltedFileName(userId,FileName);
        var NewPath = Path.Combine(path,SafeFileName);

        if (File.Exists(NewPath))
        {
            File.Delete(NewPath);
        }

        File.WriteallBytes(NewPath,Buffer);

        var Property = Value.GetType().GetProperty("FileName");
        Property.SetValue(Value,SafeFileName,null);
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


这篇文章主要讲解了“WPF如何实现带筛选功能的DataGrid”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“WPF...
本篇内容介绍了“基于WPF如何实现3D画廊动画效果”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这...
Some samples are below for ASP.Net web form controls:(from http://www.visualize.uk.com/resources/asp
问题描述: 对于未定义为 System.String 的列,唯一有效的值是(引发异常)。 For columns not defined as System.String, the only vali
最近用到了CalendarExtender,结果不知道为什么发生了错位,如图在Google和百度上找了很久,中文的文章里面似乎只提到了如何本地化(就是显示中文的月份)以及怎么解决被下拉框挡住的问题,谈
ASP.NET 2.0 page lifecyle ASP.NET 2.0 event sequence changed a lot since 1.1. Here is the order: App
静态声明: &#39; Style=&quot;position: relative&quot; AppendDataBoundItems=&quot;True&quot;&gt; (无 或 空 或
以下内容是从网络上搜集资料,然后整理而来的。不当之处,请不吝指教。(The following were from network, and edited by myself. Thanks in a
Imports System Imports System.Reflection Namespace DotNetNuke &#39;*********************************
Ok so you have all seen them: “8 million tools for web development”, “5 gagillion tools that if you