ASP.NET 5不能使用Response

我试图从我的数据库输出信息到一个Excel文件使用ASP.Net 5.在我的控制器,我有两个这样的方法。

public void ExportData() { var data = new[]{ new{ Name="Ram", Email="ram@techbrij.com", Phone="111-222-3333" }, new{ Name="Shyam", Email="shyam@techbrij.com", Phone="159-222-1596" }, new{ Name="Mohan", Email="mohan@techbrij.com", Phone="456-222-4569" }, new{ Name="Sohan", Email="sohan@techbrij.com", Phone="789-456-3333" }, new{ Name="Karan", Email="karan@techbrij.com", Phone="111-222-1234" }, new{ Name="Brij", Email="brij@techbrij.com", Phone="111-222-3333" } }; System.Web.HttpContext.Current.Response.ClearContent(); System.Web.HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=Contact.xls"); System.Web.HttpContext.Current.Response.AddHeader("Content-Type", "application/vnd.ms-excel"); WriteTsv(data, System.Web.HttpContext.Current.Response.Output); System.Web.HttpContext.Current.Response.End(); } public void WriteTsv<T>(IEnumerable<T> data, TextWriter output) { PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T)); foreach (PropertyDescriptor prop in props) { output.Write(prop.DisplayName); // header output.Write("\t"); } output.WriteLine(); foreach (T item in data) { foreach (PropertyDescriptor prop in props) { output.Write(prop.Converter.ConvertToString( prop.GetValue(item))); output.Write("\t"); } output.WriteLine(); } } 

我不得不使用System.Web,因为我不知道如何使用ASP.Net 5导出一个Excel文件,因此我目前使用的是dnx451 。 我从我的project.json中删除了dnxcore50以便使用System.Web。

但是在调用top方法时,出现以下错误:

 NullReferenceException: Object reference not set to an instance of an object. 

 System.Web.HttpContext.Current.Response.ClearContent(); 

这个代码的原始示例使用:

 Response 

代替:

 System.Web.HttpContext.Current.Response 

我不能使用只是使用响应,因为它使用Microsoft.AspNet.Http.HttpResponse而不是System.Web

使用System.Web.HttpResponse也不起作用,因为它给出了以下错误:

 An object reference is required for the non-static field, method, or property 

这是我的第一个Web应用程序,这个问题已经导致我停下来。 谁能帮我?

你不能使用System.Web。 ASP.Net Core的目标之一是去除对System.Web的依赖。 由于ASP.Net Core不依赖于System.Web,HttpContext等人。 将不会被初始化,因此NRE。 您可以使用IHttpContextAccessor在ASP.Net Core中获取HttpContext并从那里访问Response