C# - Sending and receiving HTTP Requests to REST service
<p>So I'm writing the client side user authentication code for my Web API ReST service.</p>

<p>This is how the request and response should look like and I've written this code to register a user and it works fine.</p>

<p>Http Request:</p>

<pre><code>POST https://localhost:44305/api/Account/Register HTTP/1.1
Host: localhost:44305
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:32.0) Gecko/20100101     Firefox/32.0
Accept: */*
Content-Type: application/json; charset=utf-8
X-Requested-With: XMLHttpRequest
Referer: https://localhost:44305/
Content-Length: 84
{"Email":"alice@example.com","Password":"Password1!","ConfirmPassword":"Password1!"}
</code></pre>

<p>Http Response:</p>

<pre><code>HTTP/1.1 200 OK
Server: Microsoft-IIS/8.0
Date: Wed, 01 Oct 2014 00:57:58 GMT
Content-Length: 0
</code></pre>

<p>Code to accomplish this:</p>

<pre><code>byte[] data = Encoding.UTF8.GetBytes("{\"Email\":\"alssice@example.com\"," + "\"Password\":\"Password1!\"," + "\"ConfirmPassword\":\"Password1!\"}");
WebRequest request = WebRequest.Create("http://localhost:8091/api/Account/Register");
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
request.ContentLength = data.Length;
using (Stream stream = request.GetRequestStream())
   {
     stream.Write(data, 0, data.Length);
   }
string responseContent = null;

using (WebResponse response = request.GetResponse())
 {
    using (Stream stream = response.GetResponseStream())
       {
         using (StreamReader sr99 = new StreamReader(stream))
           {
             responseContent = sr99.ReadToEnd();
           }
        }
 }

Console.WriteLine(responseContent);
</code></pre>

<p>This works fine and the user account is created in the database but I don't get the response.</p>

<p>The next problem is sending sending the login details to get a bearer token? How can I do this?<br>
This is what the request and response should look like<br></p>

<p>HTTP REQUEST FOR AUTHENTICATION:<br></p>

<pre><code>POST https://localhost:44305/Token HTTP/1.1
Host: localhost:44305
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:32.0) Gecko/20100101     Firefox/32.0
Accept: */*
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
Referer: https://localhost:44305/
Content-Length: 68

grant_type=password&amp;username=alice%40example.com&amp;password=Password1!
</code></pre>

<p>HTTP RESPONSE FOR AUTHENTICATION:</p>

<pre><code>HTTP/1.1 200 OK
Content-Length: 669
Content-Type: application/json;charset=UTF-8
Server: Microsoft-IIS/8.0 
Date: Wed, 01 Oct 2014 01:22:36 GMT

{
 "access_token":"imSXTs2OqSrGWzsFQhIXziFCO3rF...",
 "token_type":"bearer",
 "expires_in":1209599,
 "userName":"alice@example.com",
 ".issued":"Wed, 01 Oct 2014 01:22:33 GMT",
 ".expires":"Wed, 15 Oct 2014 01:22:33 GMT"
 }
</code></pre>

<p>SO how can I send a request for a token?</p>