C# 使用MVC4上传文件

C# 使用MVC4上传文件,c#,asp.net-mvc-4,C#,Asp.net Mvc 4,这是我的密码- //in Profile.cshtml @{ ViewBag.Title = "Profile"; } <h2>Profile</h2> @using (Html.BeginForm("Upload", "Profile", FormMethod.Post, new { enctype = "multipart/form-data" })) { <input type="file" name="file" /> &l

这是我的密码-

//in Profile.cshtml
@{
    ViewBag.Title = "Profile";
}

<h2>Profile</h2>

@using (Html.BeginForm("Upload", "Profile", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <input type="file" name="file" />
    <input type="submit" value="OK" />
}
}

但是每次我点击“OK”上传文件时,我都会遇到这个错误- localhost:12345/Profile/Upload-Internet explorer无法显示此网页

我的配置文件控制器中有一个名为Upload的方法,该方法应该接受此文件


我缺少什么?

您似乎没有处理动词后请求的操作方法。动作方法的默认谓词(如果未指定)是GET。虽然您的代码示例中确实有一个action方法,[HttpPost]属性被注释掉。这将使该方法仅可用于获取请求——否则您将获得404(无法显示页面)。

为什么您的HttpPost属性会被注释掉?看起来您没有操作方法来处理Post谓词,因此复制和粘贴作业是错误的。这仍然不适用于未注释掉的行。您是否在其中设置了断点以确认它从未命中该控制器操作?我只是想知道问题是否是重定向,因为没有纵断面图,也没有文件上载操作。我同意BoredBlazer的观点,你是否尝试只返回你想要的视图而不是重定向到它(例如:返回视图(“纵断面”);)?是的,我添加了一个永远不会被击中的断点。复制和粘贴作业不正确。这仍然不适用于未注释掉的行。从语法上讲,没有理由不适用。我会在action方法上设置一个断点,并确保它被命中。可能是防火墙或HttpModule首先捕获请求并阻止它——您检查过了吗?例如,您可以将UrlScan配置为阻止特定的Http谓词。
namespace MvcApplication1.Controllers
{
    public class ProfileController : Controller
    {

    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Profile() {
        return View();
    }

    [HttpPost]
    public ActionResult Upload(HttpPostedFileBase file) {
        if (file.ContentLength > 0) {
            var fileName = Path.GetFileName(file.FileName);
            var path = Path.Combine(Server.MapPath("~/Media/uploads"), fileName);
            file.SaveAs(path);
        }
        return RedirectToAction("Profile");
    }

}