If you are trying to initialize some data in your controller's constructor, you may run into an issue in which the Server
object is null. For example, the following code will throw the error:
Object reference not set to an instance of an object
public class MyController : Controller
{
private string folderPath;
public MyController()
{
// Throws an error because Server is null
folderPath = Server.MapPath("~/uploads");
// Throws an error because this.ControllerContext is null
folderPath = this.ControllerContext.HttpContext.Server.MapPath("~/uploads");
}
}
The correct place for this code is in the Initialize() method of the controller:
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
base.Initialize(requestContext);
// now Server has been initialized
folderPath = Server.MapPath("~/uploads");
}