2013-02-27 47 views
27

我想要使用ImageResizer(从ImageResizing点网)。我通过NuGet为MVC安装了ImageResizer。但是,当我去从示例使用下面的代码:HttpContext.Current不解决MVC 4项目

//Loop through each uploaded file 
foreach (string fileKey in HttpContext.Current.Request.Files.Keys) 
{ 
    HttpPostedFile file = HttpContext.Current.Request.Files[fileKey]; 
    if (file.ContentLength <= 0) continue; //Skip unused file controls. 

    //The resizing settings can specify any of 30 commands.. See http://imageresizing.net for details. 
    //Destination paths can have variables like <guid> and <ext>, or 
    //even a santizied version of the original filename, like <filename:A-Za-z0-9> 
    ImageResizer.ImageJob i = new ImageResizer.ImageJob(file, "~/uploads/<guid>.<ext>", new ImageResizer.ResizeSettings(
          "width=2000;height=2000;format=jpg;mode=max")); 
    i.CreateParentDirectory = true; //Auto-create the uploads directory. 
    i.Build(); 
} 

的“HttpContext.Current.Request.Files.Keys”在foreach没有解决?我的使用情况正确,Visual Studio不提供“解决”选项。

+0

是HttpContext.Current设置为任何东西(是否“解析”),或者你只看不到HttpContext.Current.Request.Files.Keys?这是来自你的控制器或其他类的代码吗?如果这是来自另一个类中的方法,那么确保您以某种方式将HttpContext.Current传递给它。既可以作为你调用的方法的参数,也可以有一个公共成员(HttpContext类型的)在你调用方法之前接受这个值。 – Floremin 2013-02-27 17:06:47

+0

对于您的应用程序,HttpContext.Current不是全局的。它在为请求提供服务的操作和视图中设置,但在请求周期外(如模型,实用程序类等)不存在。如果你在那里需要它,你必须从一个行动或视图中传递它,因为@Floremin说。 – 2013-02-27 17:26:24

+0

好的 - 是的,这是在我的控制器的行动。 HttpContext解析,但不是当前。我发现没有静态Current HttpContext.Request.Files,这似乎工作正常。不知道为什么静态Current不存在,可能无法从Controller“context”访问?希望我不会“遗漏”任何不使用静态的东西。谢谢! – Nick 2013-02-28 15:47:51

回答

39

问题是Controller类有一个名为HttpContext(请参阅http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.httpcontext.aspx)的公共属性。

这意味着当您尝试在控制器中使用它时没有任何限制条件时,它将解析为本地属性,而不是System.Web.HttpContext。该属性的类型是HttpContextBase里面确实有一个Request属性,你想要什么(但请注意,这是不一样的类,你会从System.Web.HttpContext得到那个会做。

88

尝试用System.Web.

前缀,如果我尝试System.Web.HttpContext.Current,那么当前是存在的,但如果我尝试HttpContext.Current,那么它不承认“当前”。我的使用语句中有System.Web,但我似乎仍需要指定它才能访问“当前”。

+1

@Chris已经回答了你为什么必须为System.Web添加前缀HttpContext,即使你在using语句中包含了System.Web。因为控制器已经具有HttpContext属性,并且如果您在没有System.Web的情况下使用,则它指向其当前没有当前属性的本地属性。 – Niraj 2015-06-17 05:50:15

2

非常简单的插件库

using System.Web; 

和替换

context.Response -> HttpContext.Current.Response 

装置

context -> HttpContext.Current 

并解决您的问题。