2010-02-15 78 views
1

我的主要目標是生成一個可以下載的XML文件。如何從ASP.NET MVC視圖生成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

您試圖創建XML或Excel文件? – 2010-02-15 19:09:29

回答

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()); 
} 
2

通過使用WebClient生成視圖似乎有點圓滿。由於Download操作已用[Authorize]屬性門控,因此您可以從Download返回XmlView()。爲了讓這樣的觀點被視爲附件,添加一個「內容處置:附件;文件名= blah.xml」頭你的迴應,就像這樣:

[HttpGet, Authorize] 
public ActionResult Download() 
{ 
    Response.Headers["Content-Disposition"] = string.Format(
     "attachment; filename=newfile{0}.xml", DateTime.Now.ToFileTime()); 
    return XmlView(); 
}