In this article, we will consume an API from the ASP.NET Razor web page where REST API is secured with API Key.
What is an API?
Web API is the Microsoft open source technology for developing REST services based on HTTP protocol. ASP.Net Web API is a framework for building, and consuming HTTP-based services. The advantage of Web API is that it can be consumed by a wide range of clients like web browsers and mobile applications. Read more about Web API.
What are Razor Web Pages?
Razor web pages are pages which are used to create cross-platform server-side HTML UI. It has specific code behind pages and is more organized. Razor pages have .cshtml file to write HTML code and .cshtml.cs file to write server-side code.
Razor web pages give you better page handling methods.
For more information Click Here to read about Razor page handler methods.
How to Secure .NET Core API using API-Key-based authentication?
Security is the main aspect while developing a web API because it is available to the outside world. API key-based authentication will create a secure communication line between client and API endpoints. Read more about – How to secure ASP.NET Core Web API using API Key Authentication?
How to consume API-key-based secure API from the Razor web page?
In this section, we will write basic HTML to create a button which will perform a POST method operation to consume a REST API.
Open Visual Studio 2019 or 2022 and create an ASP.NET Web App project.
Create a button within a form tag as shown in below code snippet.
@page "{handler?}"
@model IndexModel
<div class="col-lg-1">
<form asp-page-handler="CallAPI" method="post">
<button class="btn btn-default">Call API</button>
</form>
<br />
</div>
Now, write a function with the name OnPostCallAPI() as shown below.
You may notice that the handler name given in .cshtml is CallAPI however we have added OnPost in the function name in the code behind. Remember, OnPost is a prefix which needs to be added with each and every Post operation. For Get operation prefix will be OnGet.
public string Message { get; set; } = "Request Initiation Waiting...";
public async void OnPostCallAPI()
{
string Baseurl = "https://localhost:44309/WeatherForecast";
try
{
using (var client = new HttpClient())
{
HttpRequestMessage request = new HttpRequestMessage();
request.RequestUri = new Uri(Baseurl);
request.Method = HttpMethod.Get;
request.Headers.Add("SecureApiKey", "12345");
HttpResponseMessage response = await client.SendAsync(request);
var responseString = await response.Content.ReadAsStringAsync();
var statusCode = response.StatusCode;
if(response.IsSuccessStatusCode)
{
//API call success, Do your action
}
else
{
//API Call Failed, Check Error Details
}
}
}
catch (Exception ex)
{
throw;
}
}
How to add API Key in the Request header to authenticate REST API?
One more thing to highlight is that we have added the below line to pass the API key to authenticate the REST API.
This is because the API which we have consumed in our above code snippet needs authentication with API Key.
request.Headers.Add("SecureApiKey", "12345");
Note: If the REST API which you are calling is not secure then you do not need to add this line in your code snippet. However, if the endpoint needs an API key to authenticate then you must add this line otherwise it will throw a 401 (Unauthorized) error.
Summary
In this article, we have seen how to write basic HTML in razor web pages and how to handle OnPost and OnGet methods. After that, we have learnt how to consume a secure Restful API using ASP.NET Razor web page application.
Great job, I love this topic & especially the way you have explained it is really awesome. Thanks for sharing this info.
https://espirittech.com/dot-net-application-development-company/