Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use RestSharp.NetCore in asp.net core

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.

like image 478
San Jaisy Avatar asked Dec 30 '16 04:12

San Jaisy


People also ask

Can I use RestSharp in .NET core?

Consume the ASP.NET Core API using RestSharp. Once you've installed RestSharp into your project, you can start using it. First, you will need to create an instance of RestClient. The following code snippet shows how you can instantiate and initialize the RestClient class.

How do I use NetCore?

NET Core Application. In the middle pane on the New Project dialog box, select Console Application (. NET Core) and name it "FirstApp", then click OK. Visual Studio will open the newly created project, and you will see in the Solution Explorer window all of the files that are in this project.

How can I put my body in my RestSharp?

RestSharp supports sending XML or JSON body as part of the request. To add a body to the request, simply call AddJsonBody or AddXmlBody method of the IRestRequest instance. There is no need to set the Content-Type or add the DataFormat parameter to the request when using those methods, RestSharp will do it for you.

What is RestSharp in C#?

RestSharp is a C# library used to build and send API requests, and interpret the responses. It is used as part of the C#Bot API testing framework to build the requests, send them to the server, and interpret the responses so assertions can be made.


3 Answers

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.

like image 184
Alexey Zimarev Avatar answered Oct 06 '22 00:10

Alexey Zimarev


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.

like image 39
galdin Avatar answered Oct 05 '22 22:10

galdin


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);
}
like image 36
Antwone Antics Avatar answered Oct 05 '22 23:10

Antwone Antics