Create a Simple C# API and Access It in an HTML Page

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:

  • Open Visual Studio → Create a New ASP.NET Core Web API Project.

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

  1. Save index.html and open it in a browser.
  2. Click the "Get API Response" button.
  3. You should see : Response : Hello World


Conclusion

  • We created a simple API in C# that returns "Hello World".
  • We accessed the API from an HTML page using JavaScript.

Now you know how to build a basic API and connect it to a frontend!

Let me know if you have any questions!

要查看或添加评论,请登录

Divya Soni的更多文章

社区洞察

其他会员也浏览了