美文网首页
WebApi HelloWorld

WebApi HelloWorld

作者: MinicupSimon | 来源:发表于2018-09-19 22:17 被阅读0次
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

相关文章

网友评论

      本文标题:WebApi HelloWorld

      本文链接:https://www.haomeiwen.com/subject/gvdpnftx.html