How to generate an XML file from an ASP.NET MVC view?
My main goal is to generate an XML file that can be downloaded.
The below code succeeds in generating the file but the view (/Home/XmlView) can be accessed directly.
If I use the [Authorize] attribute on the XmlView() method then the file is created with the HTML of my default logon page.
How do get the authorization to work with the XmlView() method or do all of this more efficiently?
I am open to any any suggestions.
Thanks in advance.
using System;
using System.Net;
using System.Text;
using System.Web.Mvc;
using MvcProject.Core.Repositories;
namespace MvcProject.Core.Web.Controllers
{
[HandleError]
public class HomeController : Controller
{
private readonly IEntryRepository _entryRepository;
public HomeController(IEntryRepository entryRepository)
{
_entryRepository = entryRepository;
}
[HttpGet]
[Authorize]
public ActionResult Download()
{
var url = Url.Action("XmlView", "Home", null, "http");
var webClient = new WebClient
{
Encoding = Encoding.UTF8,
UseDefaultCredentials = true
//Credentials = CredentialCache.DefaultCredentials
};
var fileStringContent = webClient.DownloadString(url);
var fileByteContent = Response.ContentEncoding.GetBytes(fileStringContent);
return File(fileByteContent, "application/xml",
string.Format("newf开发者_开发知识库ile{0}.xml", DateTime.Now.ToFileTime()));
}
//[Authorize]
public ActionResult XmlView()
{
return View("XmlView", _entryRepository.GetAll());
}
}
}
It seems a bit round-about to generate a view through using a WebClient
. Since the Download
action is gated with an [Authorize]
attribute already, you could just return XmlView()
from Download
. To make it so the view is seen as an attachment, add a "Content-Disposition: attachment; filename=blah.xml" header to your response, like this:
[HttpGet, Authorize]
public ActionResult Download()
{
Response.Headers["Content-Disposition"] = string.Format(
"attachment; filename=newfile{0}.xml", DateTime.Now.ToFileTime());
return XmlView();
}
I didn't intend to answer my own question, but I ended up making a form with a single input (a submit button) that posts to the following method:
[HttpPost, Authorize]
public ActionResult Download()
{
Response.ContentType = "application/vnd.xls";
Response.AddHeader("content-disposition",
"attachment;filename=" +
string.Format("Registrants-{0}.xls", String.Format("{0:s}", DateTime.Now)));
return View("XmlView", _entryRepository.GetAll());
}
精彩评论