Reputation: 13
I'm trying to output information from my database to an Excel File using ASP.Net 5. In my controller I have two methods for this.
public void ExportData()
{
var data = new[]{
new{ Name="Ram", Email="[email protected]", Phone="111-222-3333" },
new{ Name="Shyam", Email="[email protected]", Phone="159-222-1596" },
new{ Name="Mohan", Email="[email protected]", Phone="456-222-4569" },
new{ Name="Sohan", Email="[email protected]", Phone="789-456-3333" },
new{ Name="Karan", Email="[email protected]", Phone="111-222-1234" },
new{ Name="Brij", Email="[email protected]", 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();
}
}
I am forced to use System.Web because I have no idea how to export an excel file using ASP.Net 5, thus I'm currently using dnx451. I deleted dnxcore50 from my project.json in order to use System.Web.
However when calling the top method, I get the following error:
NullReferenceException: Object reference not set to an instance of an object.
on
System.Web.HttpContext.Current.Response.ClearContent();
The original example of this code used:
Response
Instead of:
System.Web.HttpContext.Current.Response
I cannot use just use Response because it uses Microsoft.AspNet.Http.HttpResponse instead of System.Web
Using System.Web.HttpResponse also doesn't work because it gives the following error:
An object reference is required for the non-static field, method, or property
This is my first web application and this problem has caused me to grind into a halt. Can anyone help me?
Upvotes: 0
Views: 1437
Reputation: 31620
You can't use System.Web. One of the goals of ASP.Net Core was to remove the dependency on System.Web. Since ASP.Net Core is does not depend on System.Web the HttpContext et al. won't be initialized and hence NRE. You can use IHttpContextAccessor
to get HttpContext in ASP.Net Core and access the Response
from there.
Upvotes: 4