C# SelfHost WebAPI (2)

本文档详细介绍了如何使用C#创建并托管一个简单的SelfHost WebApi应用程序。从创建ConsoleApp项目,到添加必要的依赖库,定义ValuesController,再到配置和启动SelfHost服务,最后通过浏览器验证API接口的正确性。示例代码清晰,步骤明确,适合初学者快速上手WebApi的自托管应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

上一个自主托管Web Api 的示例存储一些问题,如下Self Host Web Api 测试OK。

1. 创建 ConsoleApp

定义项目名称: SefHostWebApiSample

2. 添加第三方组件

Microsoft.AspNet.WebApi.SelfHost

Microsoft.Net.Http

Newtonsoft.Json

在这里插入图片描述

3. 创建Controller 类 ,ValuesController.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Net;

using System.Net.Http;

using System.Web.Http;

namespace SefHostWebApiSample

{

public class ValuesController : ApiController

{

    // GET api/values

    public IEnumerable<string> Get()

    {

        return new string[] { "value1", "value2", "value3" };

    }

    // GET api/values/5

    public string Get(int id)

    {

        return "value" +id;

    }

    // POST api/values

    public void Post([FromBody] string value)

    {

    }

    // PUT api/values/5

    public void Put(int id,[FromBody] string value)

    {

    }

    // DELETE api/values/5

    public void Delete(int id)

    {

    }

}

}

4. Program.cs 中添加SelfHost代码

using System.Web.Http.SelfHost;

using System.Web.Http;

namespace SefHostWebApiSample

{

class Program

{

    static void Main(string[] args)

    {

        Uri myUri = new Uri(@"http://localhost:9999");

        // Let have our configurations readY

        HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(myUri);

        // configure routes

        config.Routes.MapHttpRoute(

            name: "DefaultApi",

            routeTemplate: "api/{controller}/{id}",

            defaults: new { id = RouteParameter.Optional }

        );

        HttpSelfHostServer server = new HttpSelfHostServer(config);

        // Start listening

        server.OpenAsync().Wait();

        Console.WriteLine("WebApi hosted on " + myUri.AbsoluteUri + " It can be tested now");

        Console.ReadLine();

    }

}

}

5. 运行App

App显示如下信息:

WebApi hosted on http://localhost:9999/ It can be tested now

在浏览器上输入:http://localhost:9999/api/values

This XML file does not appear to have any style information associated with it. The document tree is shown below.

value1

value2

value3

在浏览器上输入:http://localhost:9999/api/values/5

This XML file does not appear to have any style information associated with it. The document tree is shown
value5

测试OK !

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

flysh05

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值