📜  下载 xml 文件 asp.net web api - C# 代码示例

📅  最后修改于: 2022-03-11 14:48:48.004000             🧑  作者: Mango

代码示例1
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 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;
    }
}

// Use this below code in controller 
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; }
}