📜  dotnet create web api - C# (1)

📅  最后修改于: 2023-12-03 14:40:51.943000             🧑  作者: Mango

Dotnet Core Web API with C#

Dotnet Core is a cross-platform framework for creating web applications, console applications, and libraries that run on Windows, Linux, or macOS. In this tutorial, we will be discussing how to create a web API using C# in Dotnet Core.

Prerequisites
  • Dotnet Core SDK installed on your machine.
  • A code editor like Visual Studio Code or Visual Studio.
Creating a New Web API

To create a new web API, open your terminal or command prompt and run the following command:

dotnet new webapi -n MyWebApi

This command will create a new web API project named MyWebApi.

Understanding the Project Structure

Once the project has been created, you will see a project structure like this:

MyWebApi/
|-- Controllers/
|   |-- ValuesController.cs
|-- Properties/
|   |-- launchSettings.json
|-- appsettings.json
|-- MyWebApi.csproj
|-- Program.cs
|-- Startup.cs

Here's what these files and folders do:

  • Controllers/: This folder contains the controllers that handle incoming requests and return responses.
  • Properties/: This folder contains the project properties.
  • appsettings.json: This file contains configuration settings for the project.
  • MyWebApi.csproj: This file contains the project configuration.
  • Program.cs: This file contains the entry point for the application.
  • Startup.cs: This file contains the startup configuration for the application, including configuring services and middleware.
Creating a Controller

To create a new controller, create a new file under the Controllers/ directory and name it as per your convention. For example, MyController.cs. Then, add the following code to the file:

using Microsoft.AspNetCore.Mvc;

namespace MyWebApi.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class MyController : ControllerBase
    {
        [HttpGet]
        public IActionResult Get()
        {
            return Ok("Hello, World!");
        }
    }
}

In the above code, we have created a new controller named MyController and added a HttpGet method that will return Hello, World! when hit.

Running the Application

To run your application, navigate to the project directory in your terminal or command prompt and run the following command:

dotnet run

This command will compile and run your project. Once the project is up and running, you can navigate to http://localhost:5000/My to hit your MyController.

Congratulations! You have created a new web API using C# and Dotnet Core.

Conclusion

In this tutorial, we learned how to create a new web API project using C# and Dotnet Core, and how to create a new controller to handle incoming requests. We also learned how to run the application and hit the API endpoint.

Happy coding!