Handling Multiple QueryString Parameters With the Same Key in ASP.NET

When you are processing an HTTP request in ASP.NET you can retrieve the user-provided query string parameters using the HttpRequest.QueryString property. This property is an instance of the NameValueCollection class.

If the user has provided multiple parameters with the same key in the query string, HttpRequest.QueryString[key] will return all the values concatenated together with commas. If you would rather process the values individually, use HttpRequest.QueryString.GetValues(key), which will return an array of all the provided values.

For example:

URL: http://example.com?a=1&a=2

HttpRequest.QueryString["a"] = "1,2"
HttpRequest.QueryString.GetValues("a") = ["1", "2"]

How Return XML From ASPX in ASP.NET 1.1

I’m not sure if this is the “canonical” way to do it but here’s a description of how to write an ASP.NET 1.1 ASPX page which returns a XML document (e.g. when writing a home-brewed web service).

First, create a new Web Form (I will call it WebService.aspx). As we will be progamatically generating the XML in the HTTP response rather than sending the (processed) content of the ASPX file, delete everything from the ASPX file but the @Page directive, so that it looks something like:

<%@ Page language="c#" Codebehind="WebService.aspx.cs" AutoEventWireup="false"
    Inherits="WebService.WebService" %>

Next, open up the code-behind file WebService.aspx.cs. Within the Page_Load event handler, add the following code block:

private void Page_Load(object sender, System.EventArgs e)
{
    Response.ContentType = "text/xml";
    Response.ContentEncoding = Encoding.UTF8;

    using (TextWriter textWriter = new StreamWriter(Response.OutputStream,
                                                    Encoding.UTF8))
    {
        XmlTextWriter xmlWriter = new XmlTextWriter(textWriter);
        // Write XML using xmlWriter
    }
}

Notice the use of the HttpResponse.OutputStream property which allows us to write directly to the HTTP response body. Also notice that I explicitly set the Content-Type and Content-Encoding HTTP response headers, and that the encoding for both the response and the StreamWriter must match.

Once you have this block in place, you can use whatever technique you like to write XML to the xmlWriter object. For example, you can call XmlWriter methods by hand, pass xmlWriter as a parameter to XslTransform.Transform(), or use the XmlSerializer.

%d bloggers like this: