ASP.NET Web API(一):新建第一个项目和运行

软件版本:visual studio 2019

一、新建项目

打开软件,新建Web API项目。项目名称:test   然后创建即可。

   

 

注意,一定要选择c#语言的,我新手有次咋搞都不对,后来选了vb [泪奔]

二、添加Model和Controllers

      2.1.添加Model

         2.1.1在Models文件夹上右键,选择添加,添加 类 就行  类名称可以自定义,一般首字母大写:我定义为:Good  

 

      2.1.2在Good.cs中添加属性

        public int Id { get; set; }
        public string Name { get; set; }
        public string Category { get; set; }
        public decimal Price { get; set; }

 

         

 

  2.2.添加 Controllers

           2.2.1在Controllers文件夹上右键,选择添加,添加 控制器,选择   Web API 2控制器 -空  名称要与之前的Good对应,为Good+s+Controller,即:GoodsController

 

 

         2.2.2添加以下代码

             首先,引入test的models   (我第一次怎么搞都不对,才发现忘了写这个,哎!真不智能,原来PHP真是最好的语言)

using test.Models;

             

        添加如下代码:

        Good[] goods = new Good[]
        {
            new Good { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },
            new Good { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },
            new Good { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }
        };
        public IEnumerable<Good> GetAllProducts()
        {
            return goods;
        }
        public Good GetProductById(int id)
        {
            var product = goods.FirstOrDefault((p) => p.Id == id);
            if (product == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            return product;
        }
        public IEnumerable<Good> GetProductsByCategory(string category)
        {
            return goods.Where(
                (p) => string.Equals(p.Category, category,
                    StringComparison.OrdinalIgnoreCase));
        }

 

二、运行项目

    点击调试,自动打开浏览器。然后访问   https://localhost:44393/api/goods/    即可

 

 

                                        《----END----》

 

 

 

 

 

 

 

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

七刀

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

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

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

打赏作者

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

抵扣说明:

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

余额充值