I have a task where i need to request web api GET request with complex type parameter, I guess we don't be able to do such thing as GET request expects everything to be shared through URL.
can anyone help me on how to achieve this. Consuming Web API GET request with JSON data through C#.
Consumer Console:
class Program
{
static void Main(string[] args)
{
try
{
// Need to pass this through GET Request
var employee = new Employee() { EmployeeId = 1, EmployeeName = "Test", Designation = "Developer", Salary = 100 };
var jsonParam = JsonConvert.SerializeObject(employee);
//
var request = (HttpWebRequest)WebRequest.Create("http://localhost:52237/Values/GetEmp");
var encoding = new UTF8Encoding();
var bytes = encoding.GetBytes(jsonParam);
request.Method = "GET";
request.ContentLength = bytes.Length;
request.ContentType = "application/json";
using (var writeStream = request.GetRequestStream())
{
writeStream.Write(bytes, 0, bytes.Length);
}
using (var response = (HttpWebResponse)request.GetResponse())
{
var responseValue = string.Empty;
if (response.StatusCode == HttpStatusCode.OK)
{
// grab the response
using (var responseStream = response.GetResponseStream())
{
if (responseStream != null)
using (var reader = new StreamReader(responseStream))
{
responseValue = reader.ReadToEnd();
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
public class Employee
{
public int EmployeeId { get; set; }
public string EmployeeName { get; set; }
public int Salary { get; set; }
public string Designation { get; set; }
}
Web API:
public class ValuesController : ApiController
{
[HttpGet]
[Route("api/GetEmp")]
public Employee GetEmp([FromUri]Employee employee)
{
// Getting employee object from client
// Yet to implement
if (employee != null)
{
employee.Designation = "Engineer";
}
return employee;
}
}
public class Employee
{
public int EmployeeId { get; set; }
public string EmployeeName { get; set; }
public int Salary { get; set; }
public string Designation { get; set; }
}
Thanks in Advance.