WebApi HelloWorld

image.png

VS创建WebApi项目过程:

image.png
image.png
image.png
image.png
  • The client can decide json or xml format it wants by setting the "Accept" header in the HTTP request message.

添加Model

image.png
image.png
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

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

添加控制器

  • In Web API, a controller is an object that handles HTTP requests.
  • You don't need to put your controllers into a folder named Controllers. The folder name is just a convenient way to organize your source files.
image.png
image.png
image.png
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApiTest.Models;

namespace WebApiTest.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);
        }
    }
}


  • GetAllProducts 请求路径为: /api/products
  • GetProduct 请求路径为:/api/products/id

运行

网页


image.png
image.png

PostMan


image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 第二章——论恋爱 高三已经过去了一个月了,迎来了高三第一次月考。 对于一些同学自然是要临时抱佛脚的,但对于...
    坤杏阅读 177评论 0 0
  • 时间过得飞快,转眼间我的小宝贝林林8个月了,而他刚出生时因为吃不到奶大哭的情形还历历在目。
    漂泊的寻梦者阅读 88评论 0 0
  • 第一次遇见你的时候,你悄悄的躲在教室的教具柜后面。这也是你第一次来幼儿园吧!我们都是一样的。刚开始,你手里紧紧的抱...
    小小小粉丝阅读 203评论 0 0
  • 0.前言 此篇文章是通过github去创建Githubpages,其中的核心操作部分就是gh-pages分支的创...
    youthz阅读 937评论 0 0