26

I have gone through the http://restsharp.org/ code which work greats. Below is the code of RestSharp with out asp.net core .

public GenericResponseObject<T> GetGeneric<T>(string operation, params KeyValuePair<string, string>[] nameValues) where T : class
{
    RestClient client = new RestClient(_baseUrl)
    {
        Authenticator = new HttpBasicAuthenticator(_username, _password)
    };

    RestRequest request = new RestRequest(operation, Method.GET);

    foreach (KeyValuePair<string, string> nameValue in nameValues)
    {
        request.AddQueryParameter(nameValue.Key, nameValue.Value);
    }

    IRestResponse<GenericResponseObject<T>> response = client.Execute<GenericResponseObject<T>>(request);
        GenericResponseObject<T> responseObject = response.Data;
        return responseObject;
    }
}

This code works great to me. Now I want to implement same code in asp.net core.

Can I get a sample example how to use RestSharp in asp.net core. I have added the dependency RestSharp.NetCore": 105.2.3.

hbulens
  • 1,872
  • 3
  • 24
  • 45
San Jaisy
  • 15,327
  • 34
  • 171
  • 290

4 Answers4

47

RestSharp v106 supports .NET Standard so your code should work without changes.

RestSharp.NetCore package is not from RestSharp team and is not supported by us. It is also not being updated and the owner does not respond to messages, neither the source code of the package is published.

Dean Kuga
  • 11,878
  • 8
  • 54
  • 108
Alexey Zimarev
  • 17,944
  • 2
  • 55
  • 83
  • where is sample. i have dotnetcore web api that want to use restsharp to call my other web service but cant find any sample. or tutorial? hope you add link or sample. please – saber tabatabaee yazdi Jul 31 '18 at 13:47
  • 1
    I was actually wondering why the RestSharp.NetCore SDK sucked... Makes sense now. – Trae Moore Sep 21 '18 at 15:48
  • I couldn't get the RestSharp.Netcore nuget package to install. Just went back to RestSharp. Hopefully this will save someone some trouble. – Chris J May 16 '19 at 21:30
18

Update: I still see upvotes on this. Please follow Alexey Zimarev's answer instead. This answer was for the non-opensource RestSharp.NetCore nuget package, when the offical RestSharp package did not target .NET Standard.


Adding to Antwone Antics's answer, create an extension class:

public static class RestClientExtensions
{
    public static async Task<RestResponse> ExecuteAsync(this RestClient client, RestRequest request)
    {
        TaskCompletionSource<IRestResponse> taskCompletion = new TaskCompletionSource<IRestResponse>();
        _ = client.ExecuteAsync(request, r => taskCompletion.SetResult(r));
        return (RestResponse)(await taskCompletion.Task);
    }
}

You can now use it as follows:

var client = new RestClient(BASE_URL);
var request = new RestRequest();
// do whatever else you want/need to, to the request
// ...

// ... and use it like we used to
var response = await client.ExecuteAsync(request);

You can also create extension methods that parses the response to return a strong type and so on.

galdin
  • 12,411
  • 7
  • 56
  • 71
8

There's an existing StackOverflow question and example that calls ExecuteAsync on RestSharp.NetCore.

ExecuteAsyncPost Example in RestSharp.NetCore

I successfully used that example when referencing RestSharp.NetCore 105.2.3 with Newtonsoft.Json 9.0.2-beta2.

using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using RestSharp;

public async Task<SomeObject> TestPost(ObjectFoo foo)
{
    JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings { 
    ContractResolver = new CamelCasePropertyNamesContractResolver() 
    };

    RestClient restClient = new RestClient(API_URL);

    RestRequest request = new RestRequest("SOME_METHOD", Method.POST);
    request.AddHeader("Accept", "application/json");

    string jsonObject = JsonConvert.SerializeObject(foo, Formatting.Indented, jsonSerializerSettings);
    request.AddParameter("application/json", jsonObject, ParameterType.RequestBody);

    TaskCompletionSource<IRestResponse> taskCompletion = new TaskCompletionSource<IRestResponse>();

    RestRequestAsyncHandle handle = restClient.ExecuteAsync(
        request, r => taskCompletion.SetResult(r));

    RestResponse response = (RestResponse)(await taskCompletion.Task);

    return JsonConvert.DeserializeObject<SomeObject>(response.Content);
}
Community
  • 1
  • 1
-5

I created an extension method from it (see above comment for context).

public static class RestSharpExtensions
{
    public static RestResponse Execute(this IRestClient client, IRestRequest request)
    {
        var taskCompletion = new TaskCompletionSource<IRestResponse>();
        client.ExecuteAsync(request, r => taskCompletion.SetResult(r));
        return (RestResponse)(taskCompletion.Task.Result);
    }
}

now I can use use it as var response = restClient.Execute(request);

Irvin Dominin
  • 30,819
  • 9
  • 77
  • 111
bkorzynski
  • 541
  • 1
  • 5
  • 15
  • That's nonsense. Damaged copy of **gldraphael**'s answer. I say "copy" because it really is that, and "damaged", because it drops Task/async pattern and waits implicitly by `.Result`. – quetzalcoatl Jan 22 '18 at 11:25
  • In my case I wanted a synchronous version, therefore I actually block until I get a result. If I wanted the async version then I would have simply used the ExecuteAsync() method that is built into the framework. I think you misunderstood my use case. – bkorzynski Jan 23 '18 at 12:22
  • 1
    Can you elaborate more on "damaged"? If what I said was wrong, then I'd like to fix it so that it can help someone else. – bkorzynski Jan 23 '18 at 12:23
  • Sure. For me, implicit wait for a task is a bug. IMHO, it should explicitly `.Wait` so further maintainers will easily notice that during refactoring/etc. But more importantly, from newest `.nuget\packages\restsharp\106.2.1\lib\netstandard2.0\RestSharp.dll` in `interface IRestClient` you've got: (A) `ExecuteAsync(request,callback)` with the callback you hack via `TaskCompletionSource` into your sync way, (B) `ExecuteTaskAsync(IRestRequest request);` which you can hack into sync by just `.Result` or `.Wait`, and finally you have (C) **synchronous** `Execute(request)` - go figure. – quetzalcoatl Jan 23 '18 at 13:28