owen gerig
owen gerig

Reputation: 6172

how to make an OPTIONS request with HttpClient

How do I send an OPTIONS request with System.Net.Http.HttpClient

exposed methods for HttpClient

I was expecting a OptionsAsync

   switch (httpMethod) {
      case HTTP_METHODS.DELETE:
       {
        httpResponseMessage = httpClient.DeleteAsync(uri).Result;
        break;
       }
      case HTTP_METHODS.GET:
       {
        httpResponseMessage = httpClient.GetAsync(uri).Result;
        break;
       }
      case HTTP_METHODS.POST:
       {
        httpResponseMessage = httpClient.PostAsync(uri, httpContent).Result;
        break;
       }
      case HTTP_METHODS.PUT:
       {
        httpResponseMessage = httpClient.PutAsync(uri, httpContent).Result;
        break;
       }
      case HTTP_METHODS.OPTION:
       {
        //not sure what method to call on httpclient here to make Options request
        httpResponseMessage = httpClient.PutAsync(uri, httpContent).Result;
        if (httpResponseMessage.Headers.Contains("X-CSRF-TOKEN")) {
         IEnumerable < string > headerValues = httpResponseMessage.Headers.GetValues("X-CSRF-TOKEN");
         csrfToken = headerValues.FirstOrDefault();
        }
        break;
       } 
     }

Upvotes: 10

Views: 8974

Answers (2)

D. Siemer
D. Siemer

Reputation: 188

In order to get the expected response back, you have to make sure to set the "Origin" header in the request, like so:

using var client = new HttpClient();
var message = new HttpRequestMessage(HttpMethod.Options, "url");
message.Headers.Add("Origin", "http://example.com");
var response = await client.SendAsync(message);

Upvotes: 1

Haytam
Haytam

Reputation: 4733

There are no wrappers for that kind of methods (e.g. OPTIONS and HEAD), but you could use SendAsync just like these wrappers do:

var request = new HttpRequestMessage(HttpMethod.Options, "url");
var result = await _httpClient.SendAsync(request);

Upvotes: 10

Related Questions