【问题标题】:File upload error in asp.net mvc controller ('HttpRequestMessage' does not contain a definition for 'Files'asp.net mvc 控制器中的文件上传错误(“HttpRequestMessage”不包含“文件”的定义
【发布时间】:2018-10-29 12:37:48
【问题描述】:

我有一个用于上传的输入元素的控制器链接。在我的控制器中,我收到一个我不太理解的奇怪错误。严重性代码描述项目路径文件行抑制状态

错误 CS1061 'HttpRequestMessage' 不包含对 “文件”和没有可访问的扩展方法“文件”接受第一个 可以找到“HttpRequestMessage”类型的参数(您是否缺少 using 指令或程序集 参考?)SimSentinel C:\Users\tsach\Source\Workspaces\SIMSentinelv2\Website\SimSentinel\SimSentinel\Controllers C:\Users\tsach\Source\Workspaces\SIMSentinelv2\Website\SimSentinel\SimSentinel\Controllers\BulkSMSUploadController.cs

    using System.Data;
    using System.Linq;
    using System.Web.Http;
    using System.Web.Security;
    using Repositories.Interfaces;
    using Repositories.Interfaces.Dtos;
    using SimSentinel.Models;
    using System;
    using System.Text.RegularExpressions;
    using Newtonsoft.Json.Linq;
    using Newtonsoft.Json.Schema;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    //using System.Web.Http.HttpPut;


    namespace SimSentinel.Controllers
    {
        [System.Web.Http.Authorize]
        public class BulkSMSUploadController : ApiController
        {
          public ActionResult Index()
          {
             //ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

             //return View();
             return null; 
          }

          [System.Web.Mvc.HttpPost]
          public ActionResult UploadFiles()
          {
             if (Request.Files.Count <= 0)
             {
                return Json("No files selected.");
             }
             else
             {
                try
                {
                   HttpFileCollectionBase files = Request.Files;
                   for (int i = 0; i < files.Count; i++)
                   {
                      string path = AppDomain.CurrentDomain.BaseDirectory + "Uploads/";
                      string filename = Path.GetFileName(Request.Files[i].FileName);

                      HttpPostedFileBase file = files[i];
                      string fname;
                      if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
                      {
                         string[] testfiles = file.FileName.Split(new char[] { '\\' });
                         fname = testfiles[testfiles.Length - 1];
                      }
                      else
                      {
                         fname = file.FileName;
                      }

                      fname = Path.Combine(Server.MapPath("~/Uploads/"), fname);
                      file.SaveAs(fname);
                   }

                   return Json("File Uploaded Successfully!");
                }
                catch (Exception ex)
                {
                   return Json("Error occurred. Error details: " + ex.Message);
                }
             }
          }

          //public ActionResult About()
          //{
          //   ViewBag.Message = "Your app description page.";

          //   return View();
          //}
       }
    }

所以在这一切之后,我已经调整了我的控制器。请参阅下面的代码,但它会重定向到实际的控制器,这是 SPA 应用程序中的一个问题。此外,该文件还以奇怪的格式保存,几乎就像随机生成的字符串,如 BodyPart_2ea18b56-0c11-41f6-81ff-204bb377cbbf

using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;

public class Upload2Controller : ApiController
{
   public async Task<HttpResponseMessage> PostFormData()
   {
      // Check if the request contains multipart/form-data.
      if (!Request.Content.IsMimeMultipartContent())
      {
         throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
      }

      string root = HttpContext.Current.Server.MapPath("~/Files");
      var provider = new MultipartFormDataStreamProvider(root);

      try
      {
         // Read the form data.
         await Request.Content.ReadAsMultipartAsync(provider);

         // 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);
         }
         return Request.CreateResponse(HttpStatusCode.OK);
      }
      catch (System.Exception e)
      {
         return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
      }
   }

}

【问题讨论】:

    标签: asp.net-mvc asp.net-web-api jsajaxfileuploader


    【解决方案1】:

    您应该小心以下步骤。

    • 确保您的表单 html 元素具有 enctype = "multipart/form-data" 所以它应该类似于&lt;form action="someaction" enctype = "multipart/form-data"&gt; &lt;/form&gt;

    我通常使用 html helper..

    @using (Html.BeginForm("Index", "JobApplication", FormMethod.Post, new { @enctype = "multipart/form-data", @id = "myForm", @class = "form-horizontal" }))
        {
    // your input datas
    }
    
    • 如果你想发布图片或一些文档,而不是使用请求,你应该在你的 ViewModel 中使用public HttpPostedFileBase File { get; set; }。然后您就可以轻松地在剃须刀上使用它了。

      @Html.TextBoxFor(m => m.File, new { @type = "file", @onchange = "SomeValidationOnClientSide(this);"})

    在后端,您可以验证您的案例。就我而言,我只接受 PDF 文件..

    if ((from file in model.Files where file != null select file.FileName.Split('.')).Any(arr => arr[arr.Length - 1].ToLower() != "pdf"))
            {
                ModelState.AddModelError(string.Empty, "We only accept PDF files!");
                return View(model);
            }
            if (model.Files.Count() > 2)
            {
                ModelState.AddModelError(string.Empty,
                    "You have exceeded maximum file upload size. You can upload maximum 2 PDF file!");
                return View(model);
            }
    

    编辑:我看到您实现了 ApiController 而不是 Contoller。所以我了解到您正在开发 WEB.API,您也应该将其添加到问题标签中。

    如果你想开发 ApiController,你应该发送 byte[] 并将这个 byte[] 处理到你的 apiController 中。

    【讨论】:

      【解决方案2】:

      据我所知,您的控制器实现了 Web API 控制器(即使用 ApiController.Request),其定义如下所示:

      public System.Net.Http.HttpRequestMessage Request { get; set; }
      

      返回类型是HttpRequestMessage,它没有Files 属性,而不是预期的HttpRequestBase,它实现为以下Controller.Request 属性的返回类型:

      public System.Web.HttpRequestBase Request { get; }
      

      要解决这个问题,你需要从System.Web.Mvc.Controller基类继承,并将Web API请求移动到另一个继承ApiController的类,因为你不能在同一个类上同时继承System.Web.Mvc.ControllerSystem.Web.Http.ApiController

      namespace SimSentinel.Controllers
      {
         public class BulkSMSUploadController : Controller
         {
            [System.Web.Mvc.HttpPost]
            public ActionResult UploadFiles()
            {
               if (Request.Files.Count <= 0)
               {
                  return Json("No files selected.");
               }
               else
               {
                  try
                  {
                     HttpFileCollectionBase files = Request.Files;
                     for (int i = 0; i < files.Count; i++)
                     {
                        string path = AppDomain.CurrentDomain.BaseDirectory + "Uploads/";
                        string filename = Path.GetFileName(Request.Files[i].FileName);
      
                        HttpPostedFileBase file = files[i];
                        string fname;
                        if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
                        {
                           string[] testfiles = file.FileName.Split(new char[] { '\\' });
                           fname = testfiles[testfiles.Length - 1];
                        }
                        else
                        {
                           fname = file.FileName;
                        }
      
                        fname = Path.Combine(Server.MapPath("~/Uploads/"), fname);
                        file.SaveAs(fname);
                     }
      
                     return Json("File Uploaded Successfully!");
                  }
                  catch (Exception ex)
                  {
                     return Json("Error occurred. Error details: " + ex.Message);
                  }
               }
            }
         }
      
         [System.Web.Http.Authorize]
         public class BulkSMSUploadWebApiController : ApiController
         {
             public IHttpActionResult Index()
             {
                 return null; 
             }
         }
      }
      

      如果您想使用 Web API 控制器上传文件,您应该使用HttpResponseMessage 来检索文件详细信息,如this example 中提供的MultipartFileData(确保您首先检查IsMimeMultipartContent)。

      【讨论】:

      • 感谢大家的帮助,我不得不调整控制器中的代码以使其正常工作。所以文件现在正在保存,但我遇到了两个额外的问题。使用一些随机字符串保存的文件,如 BodyPart_2ea18b56-0c11-41f6-81ff-204bb377cbbf 并在保存后重定向到实际控制器本身,这是 SPA 应用程序中的一个问题,因为这意味着用户每次上传文件后都必须重新登录跨度>
      • 我现在将更新我的帖子,向您展示我的新控制器是什么样的
      • 2ea18b56-0c11-41f6-81ff-204bb377cbbf 似乎是一个 GUID 格式的字符串(如 8-4-4-4-12 格式)。我建议您检查file.Headers.ContentDisposition.FileNamefile.LocalFileName 以找出额外的GUID 来自哪里。
      猜你喜欢
      • 2011-11-22
      • 1970-01-01
      • 2017-01-31
      • 1970-01-01
      • 2011-02-25
      • 1970-01-01
      • 1970-01-01
      • 2017-09-25
      • 1970-01-01
      相关资源
      最近更新 更多