What is restsharp
The acronym REST stands for Representational State Transfer, this basically means that each unique URL is a representation of some object.
It is way of making a web request to web service.
Features
We can do GET, PUT, HEAD, POST, DELETE and OPTIONS
How to get started
Install a nuget package by typing restsharp
It will add reference
It is used to call api which support REST protocol.
Code
Web api 2 return json output
Get Calling code for
var apiUrl = @"http://localhost:8076/api/MyApi";
var client = new RestClient(apiUrl);
var request = new RestRequest(Method.GET);
request.AddHeader("Accept", "application/json");
var result = client.Execute(request).Content;
var
finalResult = JsonConvert.DeserializeObject<List<Student>>(result);
Full Code
Student.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace RestSharpEx.Models
{
public class Student
{
public int StudentId { get; set; }
public string Name { get; set; }
}
}
MyController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using RestSharpEx.Models;
namespace RestSharpEx.Controllers
{
public class MyApiController : ApiController
{
public IHttpActionResult
Get() {
var models = new List<Student>() {
new Student(){ StudentId=1,Name="Student1"},
new Student(){ StudentId=2,Name="Student2"},
new Student(){ StudentId=3,Name="Student3"},
};
return Ok(models);
}
}
}
Mvc - HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;
using RestSharp;
using RestSharpEx.Models;
namespace RestSharpEx.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
var apiUrl = @"http://localhost:8076/api/MyApi";
var client = new RestClient(apiUrl);
var request = new RestRequest(Method.GET);
request.AddHeader("Accept", "application/json");
var result = client.Execute(request).Content;
var finalResult = JsonConvert
.DeserializeObject<List<Student>>(result);
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your
application description page.";
return View();
}
public ActionResult
Contact()
{
ViewBag.Message = "Your contact
page.";
return View();
}
}
}
0 comments:
Post a Comment