ASP.NET MVC.如何创建接受和multipart/form-data的Action方法

ope*_*tes 9 asp.net-mvc multipartform-data

我有一个Controller方法需要接受multipart/form-data客户端作为POST请求发送.表单数据有2个部分.一个是序列化的对象application/json,另一个是发送的照片文件application/octet-stream.我的控制器上有一个方法,如下所示:

[AcceptVerbs(HttpVerbs.Post)]
void ActionResult Photos(PostItem post)
{
}
Run Code Online (Sandbox Code Playgroud)

我可以在这里Request.File没有问题地获取文件.但是PostItem为null.不知道为什么?有任何想法吗

控制器代码:

/// <summary>
/// FeedsController
/// </summary>
public class FeedsController : FeedsBaseController
{
    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Photos(FeedItem feedItem)
    {
        //Here the feedItem is always null. However Request.Files[0] gives me the file I need  
        var processor = new ActivityFeedsProcessor();
        processor.ProcessFeed(feedItem, Request.Files[0]);

        SetResponseCode(System.Net.HttpStatusCode.OK);
        return new EmptyResult();
    }
Run Code Online (Sandbox Code Playgroud)

}

电线上的客户端请求如下所示:

{User Agent stuff}
Content-Type: multipart/form-data; boundary=8cdb3c15d07d36a

--8cdb3c15d07d36a
Content-Disposition: form-data; name="feedItem"
Content-Type: text/xml

{"UserId":1234567,"GroupId":123456,"PostType":"photos",
    "PublishTo":"store","CreatedTime":"2011-03-19 03:22:39Z"}

--8cdb3c15d07d36a
Content-Disposition: file; filename="testFile.txt"
ContentType: application/octet-stream

{bytes here. Removed for brevity}
--8cdb3c15d07d36a--
Run Code Online (Sandbox Code Playgroud)

Ser*_*eit 7

FeedItem堂课是什么样的?对于我在帖子信息中看到的内容,它应该看起来像:

public class FeedItem
{
    public int UserId { get; set; }
    public int GroupId { get; set; }
    public string PublishTo { get; set; }
    public string PostType { get; set; }
    public DateTime CreatedTime { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

否则它将不受约束.您可以尝试更改操作签名,看看是否有效:

[HttpPost] //AcceptVerbs(HttpVerbs.Post) is a thing of "the olden days"
public ActionResult Photos(int UserId, int GroupId, string PublishTo
    string PostType, DateTime CreatedTime)
{
    // do some work here
}
Run Code Online (Sandbox Code Playgroud)

您甚至可以尝试HttpPostedFileBase在操作中添加参数:

[HttpPost]
public ActionResult Photos(int UserId, int GroupId, string PublishTo
    string PostType, DateTime CreatedTime, HttpPostedFileBase file)
{
    // the last param eliminates the need for Request.Files[0]
    var processor = new ActivityFeedsProcessor();
    processor.ProcessFeed(feedItem, file);

}
Run Code Online (Sandbox Code Playgroud)

如果你真的感到狂野和顽皮,请添加HttpPostedFileBaseFeedItem:

public class FeedItem
{
    public int UserId { get; set; }
    public int GroupId { get; set; }
    public string PublishTo { get; set; }
    public string PostType { get; set; }
    public DateTime CreatedTime { get; set; }
    public HttpPostedFileBase File { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

最后一段代码片段可能就是您想要的结果,但逐步细分可能对您有所帮助.

这个答案也可以帮助你顺利指向:ASP.NET MVC将Model*与*一起传递回控制器