我有一个控制器链接到一个输入元素以进行上传。在我的控制器中,我收到了一个我不太了解的怪异错误。严重性代码说明项目路径文件行抑制状态
错误CS1061'HttpRequestMessage'不包含以下定义 “文件”,并且没有可访问的扩展方法“文件”接受第一个 可以找到类型为“ HttpRequestMessage”的参数(您是否丢失了 使用指令或程序集 参考? >
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);
}
}
}
答案 0 :(得分:2)
您应该注意以下步骤。
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,新的{@ 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 []并将其处理到apiController中。
答案 1 :(得分:1)
据我所见,您的控制器实现了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.Controller
和{{1 }}在同一班上:
System.Web.Http.ApiController
如果您要使用Web API控制器上传文件,则应使用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;
}
}
}
来检索this example中提供的HttpResponseMessage
的文件详细信息(确保您正在检查{{ 1}})。