There are many ways to consume RESTFull services in client veg. WebClient etc. But, RestSharp is the wonderful to consule REST services. This provides a simple call while we want o consume services at client side.
This is easier just in three steps:
1. Create RestClient
- private readonly RestClient _client;
- private readonly string _url = ConfigurationManager.AppSettings["webapibaseurl"];
-
- public ServerDataRestClient()
- {
- _client = new RestClient(_url);
- }
In above, snippet we created a client with Base url of our services and retrieveing this url from our config file (a recommended way). Also, we can use the same as followings (not recommended)
- var client = new RestClient("http://crudwithwebapi.azurewebsites.net/");
2. Make a request
- var request = new RestRequest("api/serverdata", Method.GET) {RequestFormat = DataFormat.Json};
Here, we are calling GET resource and telling RestSharp to provide data/response in JSON format.
3. Play with response
- var response = _client.Execute<List<ServerDataModel>>(request);
Here, we are getting response :)
Complete code would look like:
- private readonly RestClient _client;
- private readonly string _url = ConfigurationManager.AppSettings["webapibaseurl"];
-
- public ServerDataRestClient()
- {
- _client = new RestClient(_url);
- }
-
- public IEnumerable<ServerDataModel> GetAll()
- {
- var request = new RestRequest("api/serverdata", Method.GET) {RequestFormat = DataFormat.Json};
-
- var response = _client.Execute<List<ServerDataModel>>(request);
-
- if (response.Data == null)
- throw new Exception(response.ErrorMessage);
-
- return response.Data;
- }
This is just a simple implementation, we can create a generic class and use the same in abstract way.