Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Languages
    • Angular Angular js Asp.net Core C C#
      DotNet HTML/CSS Java JavaScript Node.js
      Python React Security SQL Server TypeScript
  • Post Blog
  • Tools
    • Beautifiers
      JSON Beautifier HTML Beautifier XML Beautifier CSS Beautifier JS Beautifier SQL Formatter
      Dev Utilities
      JWT Decoder Regex Tester Diff Checker Cron Explainer String Escape Hash Generator Password Generator
      Converters
      Base64 Encode/Decode URL Encoder/Decoder JSON to CSV CSV to JSON JSON to TypeScript Markdown to HTML Number Base Converter Timestamp Converter Case Converter
      Generators
      UUID / GUID Generator Lorem Ipsum QR Code Generator Meta Tag Generator
      Image Tools
      Image Converter Image Resizer Image Compressor Image to Base64 PNG to ICO Background Remover Color Picker
      Text & Content
      Word Counter PDF Editor
      SEO & Web
      SEO Analyzer URL Checker World Clock
  1. Home
  2. Blog
  3. ASP.NET Core
  4. Calling Web api from Server Side using Asp.Net Core

Calling Web api from Server Side using Asp.Net Core

Date- Feb 16,2023

Updated Mar 2026

7484

Free Download Pay & Download
HttpClient Calling web api

What is HttpClient?

The HttpClient class in ASP.NET Core is a powerful tool designed for sending HTTP requests and receiving HTTP responses. It is part of the System.Net.Http namespace and provides a simple way to interact with web APIs. Developers often use HttpClient to perform operations such as GET, POST, PUT, and DELETE, making it an essential component for consuming web services.

HttpClient is designed to be reused throughout the life of an application. Creating a new instance for each request can lead to socket exhaustion due to the underlying connection pooling mechanism. Therefore, it is recommended to use a single instance of HttpClient for the entire application or use dependency injection to manage its lifecycle efficiently.

public class MyService {
    private readonly HttpClient _httpClient;

    public MyService(HttpClient httpClient) {
        _httpClient = httpClient;
    }

    public async Task GetDataAsync(string url) {
        HttpResponseMessage response = await _httpClient.GetAsync(url);
        response.EnsureSuccessStatusCode();
        return await response.Content.ReadAsStringAsync();
    }
}

Setting Up Your Project

Before you start calling web APIs, make sure to set up your ASP.NET Core project correctly. First, ensure that you have the necessary packages installed. You can install the Newtonsoft.Json package via NuGet, which is commonly used for JSON serialization and deserialization.

To install the package, you can use the following command in the Package Manager Console:

Install-Package Newtonsoft.Json

Once you have the package installed, you can start configuring your HttpClient instance. If you are using dependency injection, you can register HttpClient in your Startup.cs file:

public void ConfigureServices(IServiceCollection services) {
    services.AddHttpClient();
}

Making API Calls

To make API calls, you can create a service class that utilizes the HttpClient instance. Below is a simple example of how to perform a GET request to fetch data from a web API:

public async Task GetDepartment() {
    try {
        using (var client = new HttpClient()) {
            client.BaseAddress = new Uri("https://localhost:44347");
            HttpResponseMessage response = await client.GetAsync("api/Department/GetDepartment?id=1");
            if (response.IsSuccessStatusCode) {
                var result = await response.Content.ReadAsStringAsync();
                var department = JsonConvert.DeserializeObject(result);
                return View(department);
            }
            return View("Error");
        }
    } catch (Exception ex) {
        // Log the exception
        return View("Error");
    }
}

Handling Responses

When you receive a response from an API, it's crucial to handle it properly. The response can indicate success or failure. You should check the StatusCode property of the HttpResponseMessage to determine the outcome of your request.

In the example above, if the response is successful, we deserialize the JSON content into a C# object. If it fails, we can return an error view or handle the error based on your application's requirements. Additionally, consider implementing logging to capture any exceptions that occur during the API call.

if (response.IsSuccessStatusCode) {
    var result = await response.Content.ReadAsStringAsync();
    // Deserialize response content
} else {
    // Handle error
    var error = await response.Content.ReadAsStringAsync();
    // Log error
}

Edge Cases & Gotchas

When working with HttpClient, there are several edge cases and gotchas to be aware of:

  • Timeouts: Be mindful of request timeouts. You can set the Timeout property of HttpClient to avoid waiting indefinitely for a response.
  • Exception Handling: Network issues can result in exceptions. Always implement try-catch blocks around your API calls to handle potential errors gracefully.
  • Cancellation Tokens: Use cancellation tokens to allow the user to cancel long-running requests if necessary.

Performance & Best Practices

To optimize the performance of your API calls and ensure best practices, consider the following:

  • Reuse HttpClient: As mentioned earlier, reuse the HttpClient instance to take advantage of connection pooling.
  • Asynchronous Calls: Use asynchronous programming to prevent blocking the main thread, keeping your application responsive.
  • Handle Rate Limiting: Some APIs impose rate limits. Implement logic to handle rate limiting by retrying requests after a delay.

Conclusion

In this blog post, we have covered how to call web APIs from server-side applications using ASP.NET Core and the HttpClient class. Here are the key takeaways:

  • HttpClient is essential for making HTTP requests in ASP.NET Core.
  • Proper setup and configuration of HttpClient are crucial for optimal performance.
  • Always handle API responses and exceptions gracefully.
  • Implement best practices to improve application performance and reliability.
Call Web API From ASP.NET Core

S
Shubham Batra
Programming author at Code2Night โ€” sharing tutorials on ASP.NET, C#, and more.
View all posts โ†’

Related Articles

Posting Files to Web API in Asp.Net MVC
Jul 02, 2023
Previous in ASP.NET Core
JWT Token Authentication And Authorizations In Web API
Next in ASP.NET Core
How to upload files to Azure Blob Storage in an ASP.NET Core Web

Comments

On this page

๐ŸŽฏ

Interview Prep

Ace your ASP.NET Core interview with curated Q&As for all levels.

View ASP.NET Core Interview Q&As

More in ASP.NET Core

  • How to Encrypt and Decrypt Password in Asp.Net 25973 views
  • Exception Handling Asp.Net Core 20740 views
  • HTTP Error 500.31 Failed to load ASP NET Core runtime 20216 views
  • How to implement Paypal in Asp.Net Core 19626 views
  • Task Scheduler in Asp.Net core 17524 views
View all ASP.NET Core posts โ†’

Tags

AspNet C# programming AspNet MVC c programming AspNet Core C software development tutorial MVC memory management Paypal coding coding best practices data structures programming tutorial tutorials object oriented programming Slick Slider StripeNet
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1770
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp
Code2Night

A community platform for sharing programming knowledge, tutorials, and blogs. Learn, write, and grow with developers worldwide.

Panipat, Haryana, India
info@code2night.com
Quick Links
  • Home
  • Blog Archive
  • Tutorials
  • About Us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Guest Posts
  • SEO Analyzer
Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • SQL Formatter
  • Diff Checker
  • Regex Tester
  • Markdown to HTML
  • Word Counter
More Tools
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Base64 Encoder
  • JWT Decoder
  • UUID Generator
  • Image Converter
  • PNG to ICO
  • SEO Analyzer
By Language
  • Angular
  • Angular js
  • Asp.net Core
  • C
  • C#
  • DotNet
  • HTML/CSS
  • Java
  • JavaScript
  • Node.js
  • Python
  • React
  • Security
  • SQL Server
  • TypeScript
© 2026 Code2Night. All Rights Reserved.
Made with for developers  |  Privacy  ยท  Terms
Translate Page
We use cookies to improve your experience and analyze site traffic. By clicking Accept, you consent to our use of cookies. Privacy Policy
Accessibility
Text size
High contrast
Grayscale
Dyslexia font
Highlight links
Pause animations
Large cursor