web api从javascript下载xml文件

时间:2014-05-05 06:12:55

标签: c# asp.net-web-api

我尝试使用web api返回项目列表。

这是我的控制器:

public class RecipesController : ApiController
{
    /// <summary>
    /// Model to get recipes datas
    /// </summary>
    private readonly RecipeModel _recipeModel = new RecipeModel();

    /// <summary>
    /// Gets the recipe by division identifier.
    /// </summary>
    /// <param name="id">The div identifier.</param>
    [ActionName("Division")]
    public Adoria GetRecipeByDivisionId(int id)
    {
        return _recipeModel.GetRecipeByDivisionId(id);
    }
}

目前,这是由使用JavaScript的ASP页面调用的:

function RedirectToReport(){
var url = $("#valSelectedCheckBox").val(); // url of my web api method
location.href = url;
}

它在浏览器上显示xml文件。

我不想在浏览器上显示它,但要下载它。

你对这个目的有所了解吗?

2 个答案:

答案 0 :(得分:1)

创建此ActionResult(因此可以从应用程序的其他位置重复使用)。我从http://aspnet.codeplex.com/SourceControl/latest#Samples/WebApi/ActionResults/ActionResults/Results/OkFileDownloadResult.cs开始,这个网站有更多有用的例子。

public class OkXmlDownloadResult : IHttpActionResult
{
    private readonly ApiController _controller;

    public OkXmlDownloadResult(string xml, string downloadFileName,
        ApiController controller)
    {
        if (xml == null)
        {
            throw new ArgumentNullException("xml");
        }

        if (downloadFileName == null)
        {
            throw new ArgumentNullException("downloadFileName");
        }

        if (controller == null)
        {
            throw new ArgumentNullException("controller");
        }

        Xml = xml;
        ContentType = "application/xml";
        DownloadFileName = downloadFileName;
        _controller = controller;
    }

    public string Xml { get; private set; }

    public string ContentType { get; private set; }

    public string DownloadFileName { get; private set; }

    public HttpRequestMessage Request
    {
        get { return _controller.Request; }
    }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        return Task.FromResult(Execute());
    }

    private HttpResponseMessage Execute()
    {
        HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
        response.Content = new StringContent(Xml);
        response.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(ContentType);
        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
        {
            FileName = DownloadFileName
        };
        return response;
    }
}

然后在你的控制器中使用它(我添加了一种获取XML的简单方法,由你决定如何生成它):

public class ValuesController : ApiController
{
    public IHttpActionResult Get()
    {
        User user = new User()
        {
            FirstName = "First",
            LastName = "Last"
        };

        // Alternative 1
        XmlSerializer serializer = new XmlSerializer(typeof(User));

        // Alternative 2
        // DataContractSerializer serializer = new DataContractSerializer(typeof(User));

        StringBuilder builder = new StringBuilder();
        using (StringWriter writer = new StringWriter(builder))
        {
            serializer.Serialize(writer, user);

            // alternative 2
            // serializer.WriteObject(writer, user);
        }

        // create XML from your data.
        return new OkXmlDownloadResult(builder.ToString(), "myfile.xml", this);
    }
}

public class User
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

答案 1 :(得分:0)

尝试以下代码

public class RecipesController : ApiController
{
    private readonly RecipeModel _recipeModel = new RecipeModel();

    [ActionName("Division")]
    public HttpResponseMessage GetRecipeByDivisionId(int id)
    {
        HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);

        var adoria = _recipeModel.GetRecipeByDivisionId(id);

        XmlSerializer serializer = new XmlSerializer(typeof(Adoria));
        using (MemoryStream memoryStream = new MemoryStream())
        {
            using (XmlWriter xmlWriter = XmlWriter.Create(memoryStream))
            {
                serializer.Serialize(xmlWriter, adoria);
            }

            result.Content = new StreamContent(memoryStream);
            result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

            return result;
        }
    }
}