title: Access WebAPI with AntiForgeryToken in Aspnet 5.0 on Xamarin
body: <p>i'm trying to access a WebAPI which is using ValidateAntiForgeryToken. My WebAPI Method is this (a simple one), which is inside a User Controller (just for a test):</p>
  
  <pre><code>[HttpPost]
  [ValidateAntiForgeryToken]
  public ActionResult Test(String field)
  {
      String result = String.Empty;
      if (ModelState.IsValid)
      {
          HtmlSanitizer sanitizer = new HtmlSanitizer();
  
          try
          {
              result = sanitizer.Sanitize(field);
          }
          catch (Exception ex)
          {
              result = ex.Message;
              throw;
           }
      }
      return Json(result);
  }
  </code></pre>
  
  <p>With Ajax, i can access it with ease:</p>
  
  <pre><code>$.ajax({
      url: '/User/Test',
       type: "POST",
      contentType: "application/x-www-form-urlencoded",
  
      data: {
  
          field: self.textField(),
           __RequestVerificationToken: $("input[name='__RequestVerificationToken']").val(),
      },
      success: function(e) {
         self.textField(e)
          self.divField(e);
      },
      error: function(e) {
          console.log(e.error());
      },
  });
  </code></pre>
  
  <p>But, until now, i can't access this webapi with httpclient on xamarin. This is my code:</p>
  
  <pre><code>    private async void DoTestWebApi()
  {
      try
      {
          HttpClient clientPage = new HttpClient()
          {
              BaseAddress = new Uri("https://localhost:44356/user")
          };
  
          var pageWithToken = await clientPage.GetAsync(clientPage.BaseAddress);
  
          String verificationToken = GetVerificationToken(await pageWithToken.Content.ReadAsStringAsync());
  
          HttpClient client = new HttpClient()
          {
              BaseAddress = new Uri("https://localhost:44356/user/test/")
          };
  
          HttpRequestMessage message = new HttpRequestMessage()
          {
              RequestUri = new Uri("https://localhost:44356/user/test/"),
              Method = HttpMethod.Post
          };
  
          message.Headers.Add("__RequestVerificationToken", verificationToken);
  
          String field = "teste";
  
          //StringContent content = new StringContent("field=test", Encoding.UTF8, "application/x-www-form-urlencoded");
          StringContent content = new StringContent("__RequestVerificationToken=" + verificationToken + ",field=test", Encoding.UTF8, "application/x-www-form-urlencoded");
  
          // this doesn't work
          //client.DefaultRequestHeaders.Add("__RequestVerificationToken", verificationToken);
          var response2 = await client.SendAsync(message);
  
          if (response2.IsSuccessStatusCode)
          {
              var t = response2.Content.ReadAsStringAsync();
  
              if (true)
              {
                  // just to check if t has value
              }
          }
  
      }
      catch (Exception ex)
      {
          Console.WriteLine(ex.Message);
          throw;
      }
  
  }
  </code></pre>
  
  <p>Honestly, i don't know what else i could do to pass my anti forgery token inside the message. It works perfectly in ajax, i pass it inside the data content, but in xamarin it doesn't work. 
  All the code is executed inside the same localhost. If i remove the [ValidateAntiForgeryToken], it works. </p>
  
  <p>What am i missing?</p>
  
  <p><strong>Edit:</strong></p>
  
  <p>Ok, so now i'm sending with cookies, but is not hitting the method again. 
  This is my update:</p>
  
  <pre><code>HttpClient clientPage = new HttpClient()
  {
      BaseAddress = new Uri("https://localhost:44356/user")
  };
  
  var pageWithToken = await clientPage.GetAsync(clientPage.BaseAddress);
  
  String verificationToken = GetVerificationToken(await pageWithToken.Content.ReadAsStringAsync());
  
  List&lt;KeyValuePair&lt;String, String&gt;&gt; cookiesInfo = new List&lt;KeyValuePair&lt;String, String&gt;&gt;();
  
  foreach (var item in pageWithToken.Headers)
  {
      cookiesInfo.Add(new KeyValuePair&lt;String, String&gt;(item.Key, item.Value.ToString()));
  }
  
  cookiesInfo.Add(new KeyValuePair&lt;string, string&gt;("field", "value"));
  cookiesInfo.Add(new KeyValuePair&lt;string, string&gt;("__RequestVerificationToken", verificationToken));
  
  CookieContainer cookieContainer = new CookieContainer();
  
  using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
  {
      using (var client = new HttpClient(handler) { BaseAddress = new Uri("https://localhost:44356/user") })
      {
          var content = new FormUrlEncodedContent(cookiesInfo);
  
          cookieContainer.Add(client.BaseAddress, new Cookie("__RequestVerificationToken", verificationToken));
  
          foreach (var item in cookiesInfo)
          {
              cookieContainer.Add(client.BaseAddress, new Cookie(item.Key, item.Value));
          }
  
          var result = client.PostAsync(new Uri("https://localhost:44356/user/test"), content).Result;
  
          result.EnsureSuccessStatusCode();
      }
  
  };
  </code></pre>
  
  <p>This is driving me nuts... Ok the test is in localhost but soon this app will be in Azure, and this is a pre-requisite... </p>
  
  <hr>
  
  <p>Edit: GetVerificationToken Method:</p>
  
  <pre><code>private string GetVerificationToken(String verificationToken)
      {
          if (verificationToken != null &amp;&amp; verificationToken.Length &gt; 0)
          {
              verificationToken = verificationToken.Substring(verificationToken.IndexOf("__RequestVerificationToken"));
              verificationToken = verificationToken.Substring(verificationToken.IndexOf("value=\"") + 7);
              verificationToken = verificationToken.Substring(0, verificationToken.IndexOf("\""));
          }
  
          return verificationToken;
      }
  </code></pre>