In this article, we'll take a look at
Hide
When working with ASP.NET Web Forms applications, integrating with modern Web APIs is a common requirement. Whether you’re consuming internal APIs or third-party services, you may want to retrieve and display API data on an .aspx page. This article walks you through how to call Web API from an ASPX page and process the response using C#.
Project Scenario
You want to make an HTTP request (GET or POST) to an external or internal Web API from your ASPX code-behind (C#), read the response, and optionally deserialize the result (e.g., JSON).
Prerequisites
- ASP.NET Web Forms application (.NET Framework)
- A publicly accessible or internal RESTful API
- Basic knowledge of HttpClient and JSON
- Install-Package Newtonsoft.Json
Step-by-Step Implementation
Create a login page ASPX Page (Front-end UI)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<%@ Page Language="C#" Async="true" AutoEventWireup="true" CodeFile="Login.aspx.cs" Inherits="Login" %> <!DOCTYPE html> <html> <head runat="server"> <title>Login Page</title> </head> <body> <form id="form1" runat="server"> <div> Username: <asp:TextBox ID="txtUsername" runat="server" /> <br /> Password: <asp:TextBox ID="txtPassword" runat="server" TextMode="Password" /> <br /> <asp:Button ID="btnLogin" runat="server" Text="Login" OnClick="btnLogin_Click" /> <br /> <asp:Label ID="lblResult" runat="server" ForeColor="Red" /> </div> </form> </body> </html> |
Code-Behind (Login.aspx.cs)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
using System; using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; using Newtonsoft.Json; using System.Net.Http.Headers; public partial class Login : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { // No async in Page_Load here, handled in button click } protected async void btnLogin_Click(object sender, EventArgs e) { string username = txtUsername.Text; string password = txtPassword.Text; string apiUrl = "https://yourdomain.com/api/v1/auth/login/"; // Replace with your actual API try { using (HttpClientHandler handler = new HttpClientHandler()) { handler.UseCookies = true; handler.CookieContainer = new System.Net.CookieContainer(); using (HttpClient client = new HttpClient(handler)) { // Set request header explicitly client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded")); var formData = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("username", username), new KeyValuePair<string, string>("password", password) }); // Optional: Manually set the content type header on the content itself (though it's already handled) formData.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); HttpResponseMessage response = await client.PostAsync(apiUrl, formData); if (response.IsSuccessStatusCode) { Uri uri = new Uri(apiUrl); var cookies = handler.CookieContainer.GetCookies(uri); foreach (System.Net.Cookie cookie in cookies) { lblResult.Text += $"<br />Cookie: {cookie.Name} = {cookie.Value}"; } } else { DisplayMessage("Login failed: " + response.StatusCode); } } } } catch (Exception ex) { DisplayMessage("Oops! An error has occurred. " + ex.Message); ErrorTracking.SaveError(user.LoginID, Page.Title, "btnLogin_Click", ex); } } } |
Call Web API from an ASPX Page
Leave a Comment