Monday, June 13, 2016

Calling RESTful API in asp.net

Here, we will call the RESTful API from asp.net.

Suppose there is a RESTful API which URL is: http://localhost:8083/saveDetails

And I want to save employee information using asp.net.

We will call the above API using “POST” method.

There is a button in .aspx page. When I will click this button it will save the employee information. Data is being sent in JSON format.

Here I am using “HttpClient” to call RESTful API.

1.       Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Button ID="btnSaveDetails" runat="server" Text="Save Details" OnClick="btnSaveDetails_Click" />
        </div>
    </form>
</body>
</html>

2.       Default.aspx.cs
using System;
using System.Net.Http;
using System.Net.Http.Headers;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
       
    }

    private void saveDetails()
    {
        HttpClient client = new HttpClient();
        Uri url = new Uri("http://localhost:8083/saveDetails");
        client.BaseAddress = url;

        // Add an Accept header for JSON format.

        client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));

        System.Net.Http.HttpContent content = new StringContent(@"{""empID"":1001, ""empName"":""Shshi Bhooshan Sharma""}", System.Text.UTF8Encoding.UTF8, "application/json");

        HttpResponseMessage response = client.PostAsync(url, content).Result;
        if (response.IsSuccessStatusCode)
        {
            var result = response.Content.ReadAsStringAsync().Result;
            Response.Write(response.ReasonPhrase + "," + result);
        }
        else
        {
            Response.Write(response);
        }
    }

    protected void btnSaveDetails_Click(object sender, EventArgs e)
    {
        saveDetails();
    }
}

Hope this is helpful example for you. Leave your comment and provide your suggestion if any.

No comments:

Post a Comment