自承载 Self-Host ASP.NET Web API 1 (C#)

本教程介绍如何在控制台应用程序中托管 Web API。 ASP.NET Web API不需要 IIS。 可以在自己的主机进程中自托管 Web API。

创建控制台应用程序项目

启动 Visual Studio,然后从“开始”页中选择“新建项目”。 或者,从“ 文件 ”菜单中选择“ 新建 ”,然后选择“ 项目”。

在“ 模板 ”窗格中,选择“ 已安装的模板 ”,然后展开 “Visual C# ”节点。 在 “Visual C#”下,选择“ Windows”。 在项目模板列表中,选择“ 控制台应用程序”。 将项目命名为“SelfHost”,然后单击“ 确定”。
在这里插入图片描述

(Visual Studio 2010) 设置目标框架

如果使用 Visual Studio 2010,请将目标框架更改为 .NET Framework 4.0。 (默认情况下,项目模板以 .Net Framework 客户端配置文件为目标)

在“解决方案资源管理器”中,右键单击项目并选择“属性”。 在“目标框架”下拉列表中,将目标框架更改为 .NET Framework 4.0。 当系统提示应用更改时,单击“ 是”。
在这里插入图片描述

安装 NuGet 包管理器

NuGet 包管理器是将 Web API 程序集添加到 non-ASP.NET 项目的最简单方法。

若要检查是否安装了 NuGet 包管理器,请单击 Visual Studio 中的“工具”菜单。 如果看到名为 NuGet 包管理器的菜单项,则表示具有 NuGet 包管理器。

安装 NuGet 包管理器:

  1. 启动 Visual Studio。
  2. 在“工具”菜单上,选择“扩展和更新”。
  3. 在“扩展和汇报”对话框中,选择“联机”。
  4. 如果未看到“NuGet 包管理器”,请在搜索框中键入“nuget 包管理器”。
  5. 选择 NuGet 包管理器,然后单击“ 下载”。
  6. 下载完成后,系统会提示安装。
  7. 安装完成后,系统可能会提示重启 Visual Studio。

在这里插入图片描述

添加 Web API NuGet 包

安装 NuGet 包管理器后,将 Web API Self-Host包添加到项目中。

从“ 工具 ”菜单中,选择“ NuGet 包管理器”。 注意:如果未看到此菜单项,请确保正确安装 NuGet 包管理器。

  1. 选择“管理解决方案的 NuGet 包”
  2. 在 “管理 NugGet 包 ”对话框中,选择“ 联机”。
  3. 在搜索框中,键入“Microsoft.AspNet.WebApi.SelfHost”。
  4. 选择 ASP.NET Web API自主机包,然后单击“安装”。
  5. 安装包后,单击“ 关闭 ”关闭对话框。

备注:请确保安装名为 Microsoft.AspNet.WebApi.SelfHost 的包,而不是 AspNetWebApi.SelfHost。

在这里插入图片描述

创建模型和控制器

本教程使用与入门教程相同的模型和控制器类。

添加名为 Product的公共类。

namespace SelfHost
{
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Category { get; set; }
        public decimal Price { get; set; }
    }
}

添加名为 ProductsController的公共类。 从 System.Web.Http.ApiController 派生此类。

namespace SelfHost
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Web.Http;
    
    public class ProductsController : ApiController
    {
        Product[] products = new Product[]  
        {  
            new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },  
            new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },  
            new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }  
        };

        public IEnumerable<Product> GetAllProducts()
        {
            return products;
        }

        public Product GetProductById(int id)
        {
            var product = products.FirstOrDefault((p) => p.Id == id);
            if (product == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            return product;
        }

        public IEnumerable<Product> GetProductsByCategory(string category)
        {
            return products.Where(p => string.Equals(p.Category, category,
                    StringComparison.OrdinalIgnoreCase));
        }
    }
}

有关此控制器中的代码的详细信息,请参阅入门教程。 此控制器定义三个 GET 操作:

URI说明
/api/products获取所有产品的列表。
/api/products/id按 ID 获取产品。
/api/products/?category=category按类别获取产品列表。

托管 Web API

打开文件 Program.cs 并添加以下 using 语句:

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

将以下代码添加到 Program 类。

var config = new HttpSelfHostConfiguration("http://localhost:8080");

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

using (HttpSelfHostServer server = new HttpSelfHostServer(config))
{
    server.OpenAsync().Wait();
    Console.WriteLine("Press Enter to quit.");
    Console.ReadLine();
}

从客户端应用程序调用 Web API (C#)

让我们编写一个调用 Web API 的简单控制台应用程序。

向解决方案添加新的控制台应用程序项目:

  • 在“解决方案资源管理器”中,右键单击解决方案,然后选择“添加新项目”。

  • 创建名为“ClientApp”的新控制台应用程序。
    在这里插入图片描述
    使用 NuGet 包管理器添加 ASP.NET Web API核心库包:

  • 从“工具”菜单中,选择“ NuGet 包管理器”。

  • 选择“管理解决方案的 NuGet 包”

  • 在 “管理 NuGet 包 ”对话框中,选择“ 联机”。

  • 在搜索框中,键入“Microsoft.AspNet.WebApi.Client”。

  • 选择“Microsoft ASP.NET Web API客户端库”包,然后单击“安装”。

  • 在 ClientApp 中向 SelfHost 项目添加引用:

在“解决方案资源管理器”中,右键单击“ClientApp”项目。

  • 选择“添加引用”。
  • 在 “引用管理器 ”对话框的“ 解决方案”下,选择“ 项目”。
  • 选择 SelfHost 项目。
  • 单击" 确定"。
    在这里插入图片描述
    打开 Client/Program.cs 文件。 添加以下 using 语句:
using System.Net.Http;

添加静态 HttpClient 实例:

namespace Client
{
    class Program
    {
        static HttpClient client = new HttpClient();
    }
}

添加以下方法以列出所有产品、按 ID 列出产品以及按类别列出产品。

static void ListAllProducts()
{
    HttpResponseMessage resp = client.GetAsync("api/products").Result;
    resp.EnsureSuccessStatusCode();

    var products = resp.Content.ReadAsAsync<IEnumerable<SelfHost.Product>>().Result;
    foreach (var p in products)
    {
        Console.WriteLine("{0} {1} {2} ({3})", p.Id, p.Name, p.Price, p.Category);
    }
}

static void ListProduct(int id)
{
    var resp = client.GetAsync(string.Format("api/products/{0}", id)).Result;
    resp.EnsureSuccessStatusCode();

    var product = resp.Content.ReadAsAsync<SelfHost.Product>().Result;
    Console.WriteLine("ID {0}: {1}", id, product.Name);
}

static void ListProducts(string category)
{
    Console.WriteLine("Products in '{0}':", category);

    string query = string.Format("api/products?category={0}", category);

    var resp = client.GetAsync(query).Result;
    resp.EnsureSuccessStatusCode();

    var products = resp.Content.ReadAsAsync<IEnumerable<SelfHost.Product>>().Result;
    foreach (var product in products)
    {
        Console.WriteLine(product.Name);
    }
}

其中每种方法都遵循相同的模式:

  1. 调用 HttpClient.GetAsync 将 GET 请求发送到相应的 URI。
  2. 调用 HttpResponseMessage.EnsureSuccessStatusCode。 如果 HTTP 响应状态为错误代码,此方法将引发异常。
  3. 调用 ReadAsAsync 以从 HTTP 响应反序列化 CLR 类型。 此方法是在 System.Net.Http.HttpContentExtensions 中定义的扩展方法。
    GetAsync 和 ReadAsAsync 方法都是异步的。 它们返回表示异步操作的 Task 对象。 获取 Result 属性会阻止线程,直到操作完成。

有关使用 HttpClient 的详细信息,包括如何进行非阻止调用,请参阅 从 .NET 客户端调用 Web API。

在调用这些方法之前,请将 HttpClient 实例上的 BaseAddress 属性设置为“http://localhost:8080”。 例如:

static void Main(string[] args)
{
    client.BaseAddress = new Uri("http://localhost:8080");

    ListAllProducts();
    ListProduct(1);
    ListProducts("toys");

    Console.WriteLine("Press Enter to quit.");
    Console.ReadLine();
}

这应输出以下内容。 (请记得先运行 SelfHost 应用程序。)

1 Tomato Soup 1.0 (Groceries)
2 Yo-yo 3.75 (Toys)
3 Hammer 16.99 (Hardware)
ID 1: Tomato Soup
Products in 'toys':
Yo-yo
Press Enter to quit.

在这里插入图片描述
官网参考:https://learn.microsoft.com/zh-cn/aspnet/web-api/overview/older-versions/self-host-a-web-api

  • 19
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

劉煥平CHN

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

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

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

打赏作者

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

抵扣说明:

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

余额充值