title: Middleware to Encrypt Query string
body: <p>I am writing a .Net Core Middleware to encrypt the query string parameters, where I want to user to see something like 
  ?enc=VXzal017xHwKKPolDWQJoLACDqQ0fE//wGkgvRTdG/GgXIBDd1
  while the code sees this
  ?user=123&amp;account=456.</p>
  
  <p>I encrypt the params using a IDataProtector. The Invoke() in my middleware looks like the below code</p>
  
  <pre><code>if (UriHelper.GetEncodedUrl(context.Request).Contains("?"))
          {
              string query = ExtractQuery((context.Request.GetEncodedUrl()));
  
              int indexOfEnc = query.IndexOf(PARAMETER_NAME, StringComparison.OrdinalIgnoreCase);
  
              if (indexOfEnc &gt; -1)
              {
  
                  var enc = context.Request.Query[PARAMETER_NAME];
                  enc = Decrypt(enc);
                  context.Request.Path = new PathString(context.Request.Path.Value + enc);
                  await _next.Invoke(context);
              }
  
              else if (context.Request.Method == "GET" || context.Request.Method == "POST")
              {
                  // Encrypt the query string and redirects to the encrypted URL.
                  // Remove if you don't want all query strings to be encrypted automatically.
                  string encryptedQuery = Encrypt(query);
                  string tempRawUrl = UriHelper.GetEncodedUrl(context.Request).ToLower();
                  if (!(context.Request.Method == "POST" &amp;&amp; tempRawUrl.Contains("ha")))
                  {
                      context.Response.Redirect(context.Request.Path.Value + "?" + PARAMETER_NAME +  "=" + encryptedQuery);
                  }
              }
  
          }
          else
          {
              await _next.Invoke(context);
          }
  </code></pre>
  
  <p>The First time when I login and enter the user/pass, the code comes in to the elseif section above and gets encrypted fine. I look for the "enc" query param the next time and while it gets decrypted and the path looks good, the </p>
  
  <pre><code>**await _next.Invoke(context);**
  </code></pre>
  
  <p>in the if section does nothing. I am expecting it to go to the controller to validate the user/pass. </p>
  
  <p>Bear with me here please, this is my first middleware and I am trying to replace the httphandlers in my legacy code. </p>
  
  <p>Any help is appreciated. I have spent almost 5 hours on this and cant seem to figure it out. </p>