How can I convert this .NET RestSharp code to Micr

2020-02-26 01:14发布

I'm trying to figure out how to use HttpClient to POST some simple parameters.

  • Email
  • Password

I've been doing this with RestSharp, but I'm trying to migrate off that.

How can I do this with HttpClient, please?

I have the following RestSharp code

var restRequest = new RestRequest("account/authenticate", Method.POST);
restRequest.AddParameter("Email", email);
restRequest.AddParameter("Password", password);

How can I convert that to use the (Microsoft.Net.Http) HttpClient class, instead?

Take note: I'm doing a POST

Also, this is with the PCL assembly.

Lastly, can I add in a custom header. Say: "ILikeTurtles", "true".

3条回答
够拽才男人
2楼-- · 2020-02-26 01:24

This code isn't using HttpClient but it's using the System.Net.WebClient class, i guess it does the same thing though.

private static void Main(string[] args)
    {
        string uri = "http://www.example.com/";
        string email = "email@example.com";
        string password = "secret123";

        var client = new WebClient();

        // Adding custom headers
        client.Headers.Add("ILikeTurtles", "true");

        // Adding values to the querystring
        var query = HttpUtility.ParseQueryString(string.Empty);
        query["email"] = email;
        query["password"] = password;
        string queryString = query.ToString();

        // Uploadstring does a POST request to the specified server
        client.UploadString(uri, queryString);
    }
查看更多
一夜七次
3楼-- · 2020-02-26 01:30

If you're not opposed to using a library per se, as long as it's HttpClient under the hood, Flurl is another alternative. [disclaimer: I'm the author]

This scenario would look like this:

var result = await "http://www.example.com"
    .AppendPathSegment("account/authenticate")
    .WithHeader("ILikeTurtles", "true")
    .PostUrlEncodedAsync(new { Email = email, Password = password });
查看更多
男人必须洒脱
4楼-- · 2020-02-26 01:41

This should do it

var httpClient = new HttpClient();

httpClient.DefaultRequestHeaders.Add("ILikeTurtles", "true");

var parameters = new Dictionary<string, string>();
parameters["Email"] = "myemail";
parameters["Password"] = "password";

var result = await httpClient.PostAsync("http://www.example.com/", new FormUrlEncodedContent(parameters));
查看更多
登录 后发表回答