Search code examples
restvisual-studio-2008postasp.net-web-apiwindows-ce

Must/can I install MS ASP.NET Web API Client Libraries in order to post data to my Web API server?


Do I need to install ASP.NET Web API Client Libraries (as this article indicates) in order to post data to a Web API server? If so, can I do so in Visual Studio 2008 from a Windows CE project?

The reasons I wonder are:

0) The client is a Windows CE project, for which I'm using Visual Studio 2008, and I don't know if ASP.NET Web API Client Libraries are available for that version; I know I don't have the NuGet Package Manager in that environment.

1) I am successfully querying data from my RESTful Web API methods without installing ASP.NET Web API Client Libraries, using code like this:

while (true)
{
    deptList.departments.Clear();
    string uri = String.Format("http://platypi:28642/api/Duckbills/{0}/{1}", lastIdFetched, RECORDS_TO_FETCH);
    var webRequest = (HttpWebRequest) WebRequest.Create(uri);
    webRequest.Method = "GET";

    using (var webResponse = (HttpWebResponse)webRequest.GetResponse())
    {
        if (webResponse.StatusCode == HttpStatusCode.OK)
        {
            var reader = new StreamReader(webResponse.GetResponseStream());
            string jsonizedDuckbills = reader.ReadToEnd();
            List<Duckbill> duckbills = JsonConvert.DeserializeObject<List<Duckbill>>(jsonizedDuckbills);
            if (duckbills.Count <= 0) break;

            foreach (Duckbill duckbill in duckbills)
            {
                duckbillList.duckbills.Add(duckbill);
                lastIdFetched = duckbill.Id;
            }
        } // if ((webResponse.StatusCode == HttpStatusCode.OK)
    } // using HttpWebResponse

    int recordsAdded = LocalDBUtils.BulkInsertDuckbills(duckbillList.duckbills);
    totalRecordsAdded += recordsAdded;
} // while (true);

I'm stuck on posting, though, and the cleanest example I've seen so far for doing so is at that link already shown above.

I got an answer to my question on how to post here, but that hasn't made me smart enough yet to actually accomplish it. It's a step in the right direction, perhaps, although I reckon, based on how my client query code looks, that the client posting code would be of similar "style" (like the previously referenced article here, and unlike the likewise previously referenced answer here).

UPDATE

If I'm already providing the data in the uri string itself, as I am, like this:

string uri = String.Format("http://shannon2:28642/api/Departments/{0}/{1}", onAccountOfWally, moniker);

...why would I need to also specify it in postData? Or could I set postData (if that's just a necessary step to get the length) to those values...something like:

postData = String.Format("{0}, {1}", onAccountOfWally, moniker);

?


Solution

  • To talk to ASP.NET Web API, you do not necessarily need the client library, although it makes the life easier. After all, one of the benefits of HTTP services is the platform reach. Literally you can use any library that gives you HTTP capabilities. So, using WebRequest, you can do something like this. I'm using JSON in the payload. You can use XML and application/www-form-urlencoded as well. Just that you need to format the request body accordingly. Also, for complex objects, you will be better off using JSON.NET unlike formatting the JSON manually.

    var request = System.Net.WebRequest.Create("http://localhost:12345/api/values");
    request.Method = "POST";
    string postData = "{\"firstName\":\"Steven\"," + "\"lastName\":\"Waugh\"}";
    byte[] byteArray = Encoding.UTF8.GetBytes(postData);
    request.ContentType = "application/json";
    request.ContentLength = byteArray.Length;
    using (var requestStream = request.GetRequestStream())
    {
        requestStream.Write(byteArray, 0, byteArray.Length);
    }
    
    using (var response = request.GetResponse())
    {
        using (var responseStream = response.GetResponseStream())
        {
            using (var reader = new System.IO.StreamReader(responseStream))
            {
                string responseFromServer = reader.ReadToEnd();
                Console.WriteLine(responseFromServer);
            }
        }
    }
    

    EDIT

    If you are specifying data in URI, you do not need to specify the same in the request body. To let web API bind the parameters for you from URI, you will need to specify the route accordingly so that the placeholders are set for onAccountOfWally and moniker. Then you will need to use a simple type like string as action method parameters for web API to bind. By default, simple types are bound from URI path and query string and complex types from request body.