C# webAPI 精解

入门 创建一个web项目

先创建一个web项目 基本可以运行的程度 用postman进行接口测试
.NET Framework 和 .NET Core 都可以创建 webAPI 这里用 .NET Framework 比较简单 。
启动 Visual Studio,并从“开始”页中选择“新建项目”。 或者,在 “文件” 菜单中,选择“ 新建 ”,然后选择“ 项目”。

在 “模板 ”窗格中,选择 “已安装的模板 ”并展开 “Visual C# ”节点。 在 Visual C# 下,选择 “Web”。 在项目模板列表中,选择 ASP.NET Web 应用程序 或者直接在创建页面搜索 “ASP.NET Web 应用程序”

选择 webAPI
在这里插入图片描述

创建好先关了 概述页面
接下来要关注的文件夹只有 models 和 Controllers
在models 里添加Product 类

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

在controllers 里添加控制器 webapi 2 空 的
在这里插入图片描述
填写名称有一定要在controller 前加上对应数据类的名称 --ProductsController

入门 定义方法

定义GetAllProducts () 和 GetProduct()方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

using WebApplication1.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Http;

namespace WebApplication1.Controllers
{
    
    
    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 IHttpActionResult GetProduct(int id)
        {
    
    
            var product = products.FirstOrDefault((p) => p.Id == id);
            if (product == null)
            {
    
    
                return NotFound();
            }
            return Ok(product);
        }
    }
}

接下来直接运行就能看到我们的api了

在这里插入图片描述

如果报错 localhost 拒绝了我们的连接请求 极有可能是端口繁忙,稍等一下就正常了

输入 https://localhost:44378/api/Products 就可查看返结果
到此 web api 简单完成了

入门 操作返回结果

ASP.NET Web API如何将返回值从控制器操作转换为 HTTP 响应消息

在这里插入图片描述
如果操作返回 HttpResponseMessage,Web API 使用 HttpResponseMessage 对象的属性来填充响应,将返回值直接转换为 HTTP 响应消息。

public class ValuesController : ApiController
{
    
    
    public HttpResponseMessage Get()
    {
    
    
        HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, "value");
        response.Content = new StringContent("hello", Encoding.Unicode);
        response.Headers.CacheControl = new CacheControlHeaderValue()
        {
    
    
            MaxAge = TimeSpan.FromMinutes(20)
        };
        return response;
    } 
}

IHttpActionResult在实际使用时可以用 System.Web.Http.Results 命名空间中定义的 IHttpActionResult 实现。 ApiController 类定义返回这些内置操作结果的帮助程序方法。

其中定义了很多返回的类型可以直接调用

public IHttpActionResult Get (int id)
{
    
    
    Product product = _repository.Get (id);
    if (product == null)
    {
    
    
        return NotFound(); // Returns a NotFoundResult
    }
    return Ok(product);  // Returns an OkNegotiatedContentResult
}

入门 帮助页 和说明文档

添加 API 文档

默认情况下,帮助页包含文档的占位符字符串。 可以使用 XML 文档注释 创建文档。 若要启用此功能,请打开文件 Areas/HelpPage/App_Start/HelpPageConfig.cs 并取消注释以下行

config.SetDocumentationProvider(new XmlDocumentationProvider(
    HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml")));

下一步 勾选 , 输入生成路径
在这里插入图片描述
完成 这时给 controller上的方法写/// ///注释 会显示在帮助文档上


        /// <summary>
        /// 方法名和请求方式是一一对应的
        /// </summary>
      public IHttpActionResult GetEmployee(int id)

在这里插入图片描述

路由

猜你喜欢

转载自blog.csdn.net/qq_43886548/article/details/130966157