mvc 控制器中的文件上传错误 asp.net("HttpRequestMessage"不包含'Files'的定义



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

错误CS1061"HttpRequestMessage"不包含的定义"Files"和不可访问的扩展名方法"Files"接受第一个未能找到类型为"HttpRequestMessage"的参数(是否缺少using指令或程序集参考?(SimSentinel C:\Users\tsach\Source\Workspaces\SIMSentinelv2\Website\SimSentinel\SimSenteel\Controllers C:\Users\tsach\Source\Workspaces\SIMSenteelv2\ Website\Sim Sentinel\ SimSentinel\Contrlers\BulkSMUploadController.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应用程序中的一个问题。此外,该文件还以wierd格式保存,几乎类似于随机生成的字符串,如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);
}
}
}

您应该小心以下步骤。

  • 确保表单html元素具有enctype = "multipart/form-data"所以它应该是类似<form action="someaction" enctype = "multipart/form-data"> </form>的东西

我通常使用html助手。。

@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中。

据我所见,您的控制器实现了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来检索MultipartFileData的文件详细信息,如本例所述(请确保您首先检查IsMimeMultipartContent(。

最新更新