Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Build a generic helper for RestSharp for CRUD operations

Tags:

c#

restsharp

I have started using RestSharp to call an webapi proejct as it seems pretty easy to use.

I am wanting to build a helper class for all of my crud actions.

I have this so far for a simple PUT request.

 public static IRestResponse Update(object objectToUpdate,string apiEndPoint)
    {
        var client = new RestClient(CreateBaseUrl(null))
        {
            Authenticator = new HttpBasicAuthenticator("user", "Password1")
        };
        var request = new RestRequest(apiEndPoint, Method.PUT);
        request.AddObject(objectToUpdate);
        var response = client.Execute<MyViewModel>(request);
        //var response = client.ExecuteDynamic(request);
        return response;
    }

So the above code works however I have had to hardcode my viewmodel into it

  var response = client.Execute<MyViewModel>(request);

How can I change this so I dont need to know the type of model I am expecting?

I tried using var response = client.ExecuteDynamic(request); however this throws an exception of

Unable to cast object of type 'RestSharp.RestResponse' to type 'RestSharp.RestResponse`1[System.Object

Im not sure how I am meant to cast my object correctly

like image 329
Diver Dan Avatar asked Sep 01 '12 00:09

Diver Dan


1 Answers

I'm not familiar with RestSharp. However, it sounds like generics could help you here. Either your class or method needs to accept a type. For example, the signature of your method would change to

public static IRestResponse Update<T>(object objectToUpdate,string apiEndPoint)

This would allow you to call the method as:

Update<MyViewModel>(objectToUpdate, apiEndPoint);

Your implementation would change from your concrete type to:

var response = client.Execute<T>(request);

Overall you could modify your code to something like this:

 public static IRestResponse Update<T>(object objectToUpdate,string apiEndPoint)
{
    var client = new RestClient(CreateBaseUrl(null))
    {
        Authenticator = new HttpBasicAuthenticator("user", "Password1")
    };
    var request = new RestRequest(apiEndPoint, Method.PUT);
    request.AddObject(objectToUpdate);
    var response = client.Execute<T>(request);
    //var response = client.ExecuteDynamic(request);
    return response;
}

Documentation on C# Generics can be found here: http://msdn.microsoft.com/en-us/library/ms379564(v=vs.80).aspx

like image 100
goatshepard Avatar answered Oct 12 '22 23:10

goatshepard