title: WebException on HTTP request while debugging
body: <p>I have a ASP.NET project which involves sending HTTP requests via the Web-API Framework. The following exception is only raised when debugging:</p>
  
  <blockquote>
    <p>The server committed a protocol violation. Section=ResponseStatusLine</p>
  </blockquote>
  
  <p>The project runs perfectly if I "Start Without Debugging".</p>
  
  <p>How should I resolve this exception? </p>
  
  <p>Any help is appreciated!</p>
  
  <hr>
  
  <p><strong>Update</strong></p>
  
  <p>The problem seems related to the ASP.NET MVC Identity Framework. </p>
  
  <p>To access other Web-API methods, the client application has to first POST a <strong>login</strong> request (The login request does not need to be secure yet, and so I am sending the username and password strings directly to the Web-API POST method). If I comment out the login request, no more exception is raised.</p>
  
  <p>Below are the relevant code snippets:</p>
  
  <p><strong>The Post method:</strong></p>
  
  <pre><code>UserManager&lt;ApplicationUser&gt; UserManager = new UserManager&lt;ApplicationUser&gt;(new UserStore&lt;ApplicationUser&gt;(new ApplicationDbContext()));
  AccountAccess ac = new AccountAccess();
  
  public async Task&lt;HttpResponseMessage&gt; Post()
  {
      string result = await Request.Content.ReadAsStringAsync();
      LoginMessage msg = JsonConvert.DeserializeObject&lt;LoginMessage&gt;(result);
      HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
      var user = UserManager.Find(msg.username, msg.password);
      if (user == null)
          return response;
      if (user.Roles == null)
          return response;
      var role = from r in user.Roles where (r.RoleId == "1" || r.RoleId == "2") select r;
      if (role.Count() == 0)
      {
          return response;
      }
      bool task = await ac.LoginAsync(msg.username, msg.password);
      response.Content = new StringContent(task.ToString());
      return response;
  } 
  </code></pre>
  
  <p><strong>The Account Access class (simulating the default AccountController in MVC template):</strong></p>
  
  <pre><code>public class AccountAccess
  {
      public static bool success = false;
      public AccountAccess()
          : this(new UserManager&lt;ApplicationUser&gt;(new UserStore&lt;ApplicationUser&gt;(new ApplicationDbContext())))
      {
      }
  
      public AccountAccess(UserManager&lt;ApplicationUser&gt; userManager)
      {
          UserManager = userManager;
      }
  
      public UserManager&lt;ApplicationUser&gt; UserManager { get; private set; }
  
      public async Task&lt;bool&gt; LoginAsync(string username, string password)
      {
          var user = await UserManager.FindAsync(username, password);
          if (user != null)
          {
               await SignInAsync(user, isPersistent: false);
               return true;
          }
          else
          {
              return false;
          }
      }
      ~AccountAccess()
      {
          if (UserManager != null)
          {
              UserManager.Dispose();
              UserManager = null;
          }
      }
  
      private IAuthenticationManager AuthenticationManager
      {
          get
          {
              return HttpContext.Current.GetOwinContext().Authentication;
          }
      }
  
      private async Task SignInAsync(ApplicationUser user, bool isPersistent)
      {
          AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
          var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
          AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
      }
  }
  </code></pre>
  
  <hr>
  
  <p>Below are the relevant code snippets:</p>
  
  <p><strong>In client application:</strong></p>
  
  <pre><code>public static async Task&lt;List&lt;T&gt;&gt; getItemAsync&lt;T&gt;(string urlAction)
  {
      message = new HttpRequestMessage();
      message.Method = HttpMethod.Get;
      message.RequestUri = new Uri(urlBase + urlAction);
      HttpResponseMessage response = await client.SendAsync(message);
      string result = await response.Content.ReadAsStringAsync();
      List&lt;T&gt; msgs = JsonConvert.DeserializeObject&lt;List&lt;T&gt;&gt;(result);
      return msgs;
  }
  </code></pre>
  
  <p><strong>In Web-API controller:</strong></p>
  
  <pre><code>public HttpResponseMessage Get(string id)
  {
      HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
      if (id == "ItemA")
      {
          List&lt;ItemAMessage&gt; msgs = new List&lt;ItemAMessage&gt;();
  
          // some code...
  
          response.Content = new StringContent(JsonConvert.SerializeObject(msgs));
      }
      else if (id == "ItemB")
      {
           List&lt;ItemBMessage&gt; msgs = new List&lt;ItemBMessage&gt;();
  
          // some code...
  
          response.Content = new StringContent(JsonConvert.SerializeObject(msgs));
      }
      return response;
  }
  </code></pre>
  
  <p>Some observations I have:</p>
  
  <ol>
  <li>I thought that I may need to send the request asynchronously (with the <code>async-await</code> syntax), but the exception still persists that way.</li>
  <li>If I step through the code, the request <strong>does</strong> enter the HTTP method, but the code breaks at random line (Why?!) before returning the response, so I assume no response is being sent back.</li>
  <li>I have tried the following solutions, as suggested in answers to similar questions, none of which works for me:
  
  <ul>
  <li>Setting <code>useUnsafeHeaderParsing</code> to <code>true</code></li>
  <li>Adding the header <code>Keep-Alive: false</code></li>
  <li>Changing the port setting of Skype (I don't have Skype, and port 80 and 443 are not occupied)</li>
  </ul></li>
  </ol>
  
  <p>Additional information, in case they matter:</p>
  
  <ul>
  <li>Mac OS running Windows 8.1 with VMware Fusion</li>
  <li>Visual Studio 2013 </li>
  <li>.NET Framework 4.5</li>
  <li>IIS Express Server</li>
  </ul>
  
  <hr>
  
  <p><strong>Update 2</strong></p>
  
  <p>The exception is resolved, but I am unsure of which modification did the trick. AFAIK, either one or both of the following fixed it:</p>
  
  <ul>
  <li>I have a <code>checkConnection()</code> method, which basically sends a GET request and return true on success. I added <code>await</code> to the <code>HttpClient.SendAsync()</code> method and enforced <strong>async all the way up</strong>.</li>
  <li>I retracted all code in the MainWindow constructor, except for the <code>InitializeComponent()</code> method, into the Window Initialized event handler.</li>
  </ul>
  
  <p>Any idea?  </p>
  
  <p>Below are relevant code to the modifications illustrated above:</p>
  
  <p><strong>the checkConnectionAsync method:</strong></p>
  
  <pre><code>public static async Task&lt;bool&gt; checkConnectionAsync()
  {
      message = new HttpRequestMessage();
      message.Method = HttpMethod.Get;
      message.RequestUri = new Uri(urlBase);
      try
      {
          HttpResponseMessage response = await client.SendAsync(message);
          return (response.IsSuccessStatusCode);
      }
      catch (AggregateException)
      {
          return false;
      }
  }
  </code></pre>
  
  <p><strong>Window Initialized event handler (retracted from the MainWindow constructor):</strong></p>
  
  <pre><code>private async void Window_Initialized(object sender, EventArgs e)
  {
      if (await checkConnectionAsync())
      {
          await loggingIn();
          getItemA();
          getItemB();
      }
      else
      {
          logMsg.Content = "Connection Lost. Restart GUI and try again.";
      }
  }
  </code></pre>
  
  <hr>
  
  <p><strong>Update 3</strong></p>
  
  <p>Although this may be a little off-topic, I'd like to add a side note in case anyone else falls into this – <strong>I have been using the wrong authentication approach for Web-API to start with.</strong> The Web-API project template already has a built-in Identity framework, and I somehow "replaced" it with a rather simple yet broken approach... </p>
  
  <p><a href="https://www.youtube.com/watch?v=dk0PwKO4MP0" rel="noreferrer">This video</a> is a nice tutorial to start with.</p>
  
  <p><a href="http://www.asp.net/web-api/overview/security/individual-accounts-in-web-api" rel="noreferrer">This article</a> provides a more comprehensive explanation.</p>