How to return XML in ASP.NET?

前端 未结 9 1463
粉色の甜心
粉色の甜心 2020-11-28 20:17

I have encountered many half-solutions to the task of returning XML in ASP.NET. I don\'t want to blindly copy & paste some code that happens to work most of the time, th

9条回答
  •  甜味超标
    2020-11-28 20:23

    Ideally you would use an ashx to send XML although I do allow code in an ASPX to intercept normal execution.

    Response.Clear()
    

    I don't use this if you not sure you've dumped anything in the response already the go find it and get rid of it.

    Response.ContentType = "text/xml"
    

    Definitely, a common client will not accept the content as XML without this content type present.

     Response.Charset = "UTF-8";
    

    Let the response class handle building the content type header properly. Use UTF-8 unless you have a really, really good reason not to.

    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.Cache.SetAllowResponseInBrowserHistory(true);
    

    If you don't send cache headers some browsers (namely IE) will cache the response, subsequent requests will not necessarily come to the server. You also need to AllowResponseInBrowser if you want this to work over HTTPS (due to yet another bug in IE).

    To send content of an XmlDocument simply use:

    dom.Save(Response.OutputStream);
    

    dom.Save(Response.Output);
    

    Just be sure the encodings match, (another good reason to use UTF-8).

    The XmlDocument object will automatically adjust its embedded encoding="..." encoding to that of the Response (e.g. UTF-8)

    Response.End()
    

    If you really have to in an ASPX but its a bit drastic, in an ASHX don't do it.

提交回复
热议问题