Simple Web API - Dotnet frame work

 Here's an example of a ASP.NET Framework Web API and how it can be called from another ASP.NET Web application:

1. ASP.NET Framework Web API (WebApiProject)

This project will define a simple API controller with a GET endpoint that returns a list of strings.

  • Create a new ASP.NET Web Application project in Visual Studio and name it "WebApiProject".
  • Install the Microsoft.AspNet.WebApi.Client NuGet package to enable calling web APIs.

WebApiProject/Controllers/ValuesController.cs:

Code snippet
using System.Collections.Generic; using System.Web.Http; namespace WebApiProject.Controllers { public class ValuesController : ApiController { // GET: api/values public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } } }

2. ASP.NET Web Application (WebAppProject)

This project will call the Web API endpoint and display the returned data.

  • Create a new ASP.NET Web Application project in Visual Studio and name it "WebAppProject".

WebAppProject/Default.aspx.cs:

Code snippet
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : Page
{
    protected async void Button1_Click(object sender, EventArgs e)
    {
        //  Base URL of the Web API project
        string baseUrl = "http://localhost:your_port/api/";

        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(baseUrl);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response = await client.GetAsync("values");

            if (response.IsSuccessStatusCode)
            {
                var data = await response.Content.ReadAsAsync<IEnumerable<string>>();
                ResultLabel.Text = string.Join(",", data);
            }
            else
            {
                ResultLabel.Text = "Error calling API";
            }
        }
    }
}

Default.aspx:

HTML
<!DOCTYPE html>
<html lang="en"> <head> <title>Call Web API</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Button ID="Button1" runat="server" Text="Call API" OnClick="Button1_Click" /> </div> <br /> <asp:Label ID="ResultLabel" runat="server" Text=""></asp:Label> </form> </body> </html>

Explanation:

  1. The ValuesController in WebApiProject defines a simple GET endpoint that returns a list of strings.
  2. The Default.aspx.cs code in WebAppProject uses HttpClient to call the Web API endpoint.
  3. It sets the base URL of the Web API and configures the Accept header for JSON data.
  4. The code performs an asynchronous GET request and checks the response status code.
  5. If successful, it reads the response content as a list of strings and displays them on the label.

Running the example:

  1. Run the WebApiProject first (it should be hosted somewhere, like IIS Express).
  2. Run the WebAppProject.
  3. Click the "Call API" button. You should see "value1,value2" displayed on the label.

This is a basic example. You can adapt it to your specific needs, including:

  • Different API endpoints with various HTTP methods (GET, POST, PUT, etc.)
  • Passing data to the API endpoint in the request body.
  • Handling different response formats (JSON, XML, etc.).
  • Implementing security measures (authentication, authorization) for the API.

For more advanced features and practices, consider using ASP.NET Core for both Web API and web application development.

Post a Comment

Previous Post Next Post