要在 C# 控制台中创建 Web API 服务,需要按照以下步骤:

  1. 打开 Visual Studio,并创建一个新的控制台应用程序项目。

  2. 在项目中添加以下 NuGet 包:Microsoft.AspNet.WebApi.Core、Microsoft.AspNet.WebApi.SelfHost。

  3. 在程序的 Main 方法中编写以下代码:

using System;
using System.Web.Http;
using System.Web.Http.SelfHost;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            var config = new HttpSelfHostConfiguration("http://localhost:8080");

            config.Routes.MapHttpRoute(
                name: "API Default",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            var server = new HttpSelfHostServer(config);
            server.OpenAsync().Wait();

            Console.WriteLine("Web API服务已启动,按任意键停止...");
            Console.ReadKey();

            server.CloseAsync().Wait();
        }
    }
}

此代码将创建一个 Web API 服务,并将其绑定到本地计算机的端口 8080 上。

  1. 创建一个控制器类,该类将处理 Web API 请求。例如:
using System.Web.Http;

namespace ConsoleApp1.Controllers
{
    public class HelloWorldController : ApiController
    {
        public string Get()
        {
            return "Hello, world!";
        }
    }
}

此代码将创建一个名为 HelloWorldController 的控制器,并为其添加一个 Get 方法,该方法将返回字符串“Hello, world!”。

  1. 运行程序,在浏览器中打开 http://localhost:8080/api/helloworld,应该会看到“Hello, world!”的响应。

这就是在 C# 控制台中创建 Web API 服务的基本步骤。可以根据需要添加更多控制器和方法。

c# 用控制台创建一个webapi服务

原文地址: https://www.cveoy.top/t/topic/Zv0 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录