11

multipart/form-dataクライアントからの送信をPOSTリクエストとして受け入れる必要があるControllerメソッドがあります。フォームデータには2つの部分があります。1つはシリアル化されたオブジェクトで、もう1つはapplication/jsonとして送信される写真ファイルですapplication/octet-stream。私のコントローラーには次のようなメソッドがあります。

[AcceptVerbs(HttpVerbs.Post)]
void ActionResult Photos(PostItem post)
{
}

ここで問題なくファイルを取得できますが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();
    }

}

回線上のクライアント要求は次のようになります。

{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--
4

2 に答える 2

6

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; }
}

それ以外の場合はバインドされません。アクション署名を変更してみて、これが機能するかどうかを確認できます。

[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
}

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);

}

そして、あなたが本当にワイルドでいたずらだと感じているなら、以下に追加HttpPostedFileBaseして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; }
    public HttpPostedFileBase File { get; set; }
}

この最後のコード スニペットはおそらくあなたが最終的に望むものですが、段階的な内訳が役立つかもしれません。

この回答は、正しい方向にも役立つ可能性があります。ASP.NET MVC は、モデルを *一緒に* ファイルと共にコントローラーに渡します。

于 2011-03-19T10:42:14.293 に答える
2

@Sergi が言うように、HttpPostedFileBase ファイル パラメータをアクションに追加します。MVC3 についてはわかりませんが、1 と 2 については、次のように multipart/form-data を投稿することをフォーム/ビューで指定する必要があります。

<% using (Html.BeginForm(MVC.Investigation.Step1(), FormMethod.Post, new { enctype = "multipart/form-data", id = "step1form" }))

そして、これは私のコントローラにあります:

[HttpPost]
    [ValidateAntiForgeryToken]
    [Authorize(Roles = "Admin, Member, Delegate")]
    public virtual ActionResult Step1(InvestigationStep1Model model, HttpPostedFileBase renterAuthorisationFile)
    {
        if (_requesterUser == null) return RedirectToAction(MVC.Session.Logout());

        if (renterAuthorisationFile != null)
        {
            var maxLength = int.Parse(_configHelper.GetValue("maxRenterAuthorisationFileSize"));
            if (renterAuthorisationFile.ContentLength == 0)
            {
                ModelState.AddModelError("RenterAuthorisationFile", Resources.AttachAuthorizationInvalid);
            }
            else if (renterAuthorisationFile.ContentLength > maxLength * 1024 * 1204)
            {
                ModelState.AddModelError("RenterAuthorisationFile", string.Format(Resources.AttachAuthorizationTooBig, maxLength));
            }
        } 
        if(ModelState.IsValid)
        {
            if (renterAuthorisationFile != null && renterAuthorisationFile.ContentLength > 0)
            {
                var folder = _configHelper.GetValue("AuthorizationPath");
                var path = Server.MapPath("~/" + folder);
                model.RenterAuthorisationFile = renterAuthorisationFile.FileName;
                renterAuthorisationFile.SaveAs(Path.Combine(path, renterAuthorisationFile.FileName));
            }
            ...
            return RedirectToAction(MVC.Investigation.Step2());
        }
        return View(model);
    }

それが役に立てば幸い!

于 2011-03-19T15:42:17.370 に答える