Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

How to Pass a Large String to a Web API Method (Apart from the URI)

0.00/5 (No votes)
27 Feb 2014 1  
Pass a long string to a Web API method (not as part of the URI query)

Passing S.O.U.S. "Under the Table" to a Web API Method

Once you know how, it's easy to pass a S.O.U.S. (String Of Unusual Size - see the movie "The Princess Bride" if you don't understand that) to a Web API method. Here's how:

CLIENT Code

private void button1_Click(object sender, EventArgs e)
{
    ProcessRESTPostXMLFileAsStr
    ("http://Platypus:28642/api/Platypi/PostArgsAndXMLFileAsStr?serialNum=192837465&siteNum=42");
}

private void ProcessRESTPostXMLFileAsStr(string uri)
{
    using (var client = new WebClient())
    {
        client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
        StringBuilder sb = new StringBuilder();
        using (StreamReader sr = new StreamReader(@"C:\Platypus\eXtraneousMothLepidoptera.XML"))
        {
            String line;
            while ((line = sr.ReadLine()) != null)
            {
                sb.AppendLine(line);
            }
        }
        // I don't know why the prepended equals sign is necessary, but it is
        string allLines = "=" + sb.ToString();
        var result = client.UploadString(uri, "POST", allLines);
    }            
}

Obviously (hopefully), you need to replace the IP Address, Port, Controller name, and arg vals in the ProcessRESTPostXMLFileAsStr() arg, also the location of the file to read in that method.

Here, Now, is the SERVER (Web API App) Code

[Route("api/Platypi/PostArgsAndXMLFileAsStr")]
public void PostArgsAndXMLFileAsStr([FromBody] string value, string serialNum, string siteNum)
{
    string s = string.Format("{0}{1}{2}", value, serialNum, siteNum);
    // Parsing the contents of the stringified XML left as an exercise to the exorcist
}

You're Welcome

If you like this tip, respond with "as you wish" the next time your parent, child, spouse, or significant duckbilled platypus requests something of you. Again, see the aforelinked flick if your grokMeter is ululating.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here