我的主要目标是生成一个可以下载的XML文件。
以下代码成功生成文件,但可以直接访问视图(/ Home / XmlView)。
如果我在XmlView()方法上使用[Authorize]属性,则使用我的默认登录页面的HTML创建该文件。
如何获得使用XmlView()方法的授权或更有效地完成所有这些操作?
我愿意接受任何建议。
提前致谢。
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("newfile{0}.xml", DateTime.Now.ToFileTime()));
}
//[Authorize]
public ActionResult XmlView()
{
return View("XmlView", _entryRepository.GetAll());
}
}
}
答案 0 :(得分:2)
通过使用WebClient
生成视图似乎有点圆。由于Download
操作已经使用[Authorize]
属性进行了门控,因此您可以从XmlView()
返回Download
。要使视图被视为附件,请在响应中添加“Content-Disposition:attachment; filename = blah.xml”标题,如下所示:
[HttpGet, Authorize]
public ActionResult Download()
{
Response.Headers["Content-Disposition"] = string.Format(
"attachment; filename=newfile{0}.xml", DateTime.Now.ToFileTime());
return XmlView();
}
答案 1 :(得分:0)
我不打算回答我自己的问题,但我最终制作了一个带有单个输入(提交按钮)的表单,该表单发布到以下方法:
[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());
}