Create a Simple C# API and Access It in an HTML Page
Step 1: Create a Simple API in C#
Follow these steps to create a basic API using ASP.NET Core.
1?? Create a New ASP.NET Core API Project
Run this command in the terminal:
dotnet new webapi -n MySimpleAPI
cd MySimpleAPI
OR, if using Visual Studio:
2?? Add a GetCustomer API Endpoint
Open Controllers/WeatherForecastController.cs and replace the content with this:
using Microsoft.AspNetCore.Mvc;
[Route("api/[controller]")]
[ApiController]
public class CustomerController : ControllerBase
{
[HttpGet]
public string GetCustomer()
{
return "Hello World";
}
}
3??Run the API
Start the API:
dotnet run
Now, open the browser and visit: https://localhost:7222/api/Customer
You should see:
领英推荐
Hello World
Step 2: Access the API from an HTML Page
Create a simple index.html file with this code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>API Call Example</title>
<script>
async function fetchData() {
try {
const response = await fetch("https://localhost:7222/api/Customer");
const data = await response.text();
document.getElementById("output").innerText = "Response: " + data;
} catch (error) {
document.getElementById("output").innerText = "Error fetching data!";
}
}
</script>
</head>
<body>
<h2>API Response</h2>
<button onclick="fetchData()">Get API Response</button>
<p id="output"></p>
</body>
</html>
Step 3: Run the HTML Page
Conclusion
Now you know how to build a basic API and connect it to a frontend!
Let me know if you have any questions!