Passing String to Web API method (not on the URI)

by clayshannon

HTML

<h2>Passing S.O.U.S. "Under the Table" to a Web API Method</h2>
<p>Once you know how, it's easy to pass a S.O.U.S. (String Of Unusual Size - see the movie "The Princess Bride" <a href="http://www.amazon.com/exec/obidos/ASIN/B000VEPL2M/garrphotgall-20" target="_blank"><img height="160" width="107" 

src="http://ecx.images-amazon.com/images/I/51CQK1J5sXL._SL160_.jpg" /></a> if you don't understand that) to a Web API method. Here's how:</p>

<h3>CLIENT code</h3>
<pre lang="cs">
        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);
                MessageBox.Show(result);
            }            
        }
</pre>

<p>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.</p>

<p>Here, now, is the server (Web API app) code:</p>

<pre lang="cs">
        [Route("api/Platypi/PostArgsAndXMLFileAsStr")]
        public void PostArgsAndXMLFileAsStr([FromBody] string...