Replace RestSharp GET request with Net.Http

1.7k Views Asked by At

I have a RestSharp Entitlement check code that works, but I need to replace it with one that uses native C# library (Net.Http). So I was wondering what will the equivalent of my code be using native C#.

Here is my code:

        public static bool Entitlement(string appId, string userId)
    {
        //REST API call for the entitlement API.
        //We are using RestSharp for simplicity.
        //You may choose to use another library.

        //(1) Build request
        var client = new RestClient();
        client.BaseUrl = new System.Uri(@"https://apps.example.com/");

        //Set resource/end point
        var request = new RestRequest();
        request.Resource = "webservices/checkentitlement";
        request.Method = Method.GET;

        //Add parameters
        request.AddParameter("userid", userId);
        request.AddParameter("appid", appId);

        //(2) Execute request and get response
        IRestResponse response = client.Execute(request);

        //Get the entitlement status.
        bool isValid = false;
        if (response.StatusCode == HttpStatusCode.OK)
        {
            JsonDeserializer deserial = new JsonDeserializer();
            EntitlementResponse entitlementResponse = deserial.Deserialize<EntitlementResponse>(response);
            isValid = entitlementResponse.IsValid;
        }

        //
        return isValid;
    }


    class EntitlementResponse
{
    public string UserId { get; set; }
    public string AppId { get; set; }
    public bool IsValid { get; set; }
    public string Message { get; set; }
}
1

There are 1 best solutions below

2
Serge On

try this

public async Task<EntitlementResponse> Entitlement(string appId, string userId)
{
using (var client = new HttpClient())
{
    var baseAddress ="https://apps.example.com/";

var api = "/webservices/checkentitlement/"+  userId.ToString()+"/" + appId.ToString();

//or since I don't know how your API looks
var api = "/webservices/checkentitlement?userId="+  userId.ToString()+"&appId=" + appId.ToString()

    client.BaseAddress = new Uri(baseAddress);
    var contentType = new MediaTypeWithQualityHeaderValue("application/json");
    client.DefaultRequestHeaders.Accept.Add(contentType);
    var response = await client.GetAsync(api);
    var statusCode = response.StatusCode.ToString();
    if (response.IsSuccessStatusCode)
    {
        var json = await response.Content.ReadAsStringAsync();
        return JsonConvert.DeserializeObject<EntitlementResponse>(json);
    }
}
return null;
}