Asp.Net WebApi服务的创建

Web API一种REST架构风格的Web服务。所谓的REST架构与技术无关,而是面向资源的一种软件架构设计。

WCF自3.5之后也提供了对REST风格的支持,但和WebAPI来比较显得较为笨重,WebAPI提供了更轻量级的通信架构。

我们看如何创建一个WebAPI服务

首先新建一个solution,并在该solution下面新建一个WebApi Project,如图

在新建的WebAPI项目中,新加Controller(类似于MVC的创建),我们起名叫CustomerController,在CustomerController中我们提供对Customer数据

简单的添加和查询功能。具体的需要调用仓储来实现内部逻辑处理,仓储类代码如下

复制代码
//Model类
namespace CustomerService.Models {     public class Customer     {         public int ID { get; set; }         public string Name { get; set; }         public string Email { get; set; }     } }
namespace CustomerService.Repository
{
    public interface ICustomerRepository
    {
        Customer GetCustomer(int id);
  
        int Add(Customer customer);
    }
}
namespace CustomerService.Repository
{
    public class CustomerRepository : ICustomerRepository
    {
        private static List<Customer> customers = new List<Customer>()
        {
            new Customer()
            {
                ID = 1,
                Name = "zhangsan",
                Email = "zhangsan@dx.com"
            },
            new Customer()
            {
                ID = 2,
                Name = "lisi",
                Email = "lisi@dx.com"
            },
            new Customer()
            {
                ID = 3,
                Name = "wangwu",
                Email = "wangwu@dx.com"
            }
        };
 
        public Customer GetCustomer(int id)
        {
            return customers.FirstOrDefault(c => c.ID == id);
        }
  
        public int Add(Customer customer)
        {
            int maxId = 0;
            if (customers != null)
            {
                maxId = customers.Max(c => c.ID);
                customer.ID = maxId;
                customers.Add(customer);
            }
            return maxId;
        } 
    }
}
复制代码

下面就来看一下Controller的代码


复制代码
namespace CustomerService.Controllers
{
    public class CustomerController : ApiController
    {
        private ICustomerRepository customerRepository;
 
        public CustomerController()
        {
            customerRepository = new CustomerRepository();
        }
 
        public Customer GetCustomerById(int id)
        {
            return customerRepository.GetCustomer(id);
        }
 
        public int AddCustomer(Customer customer)
        {
            return customerRepository.Add(customer);
        }
    }
}
复制代码

以上是对Web API服务的创建步骤。WebAPI中也存在路由配置,可以对服务的地址进行个性化。具体是在项目中自动生成的App_Start文件加下WebApiConfig.cs中配置,代码如下

复制代码
namespace CustomerService
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();

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

            config.Routes.MapHttpRoute(
                name: "AddCustomer",
                routeTemplate: "api/{controller}/add",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}
复制代码

上面的代码是在Application_Start()方法中调用的(新建WebAPI项目的时候自动生成好的)

复制代码
namespace CustomerService
{
    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);
        }
    }
}
复制代码

至此,我们的第一个WebAPI服务已经创建成功,启动运行该项目后(服务已启动状态),在浏览器(Chrom)中输入服务的地址查询单个Customer

http://localhost:24434/api/customer/1 浏览器会展示出Xml格式的结果

 

 

posted on   One heart  阅读(1988)  评论(0编辑  收藏  举报

编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示