c# webapi 开发

首先创建一个项目,web-----》webapi----控制器添加一个控制器ProductsController

不多说直接上代码:

 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 } 
        };


        //
        // GET: /Products/


        public IEnumerable<Product> GetAllProducts()
        {
            return products;
        }




        public Product GetProductById(int id)
        {
            var product = products.FirstOrDefault((p) => p.Id == id);
            if (product == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            return product;
        }



        public IEnumerable<Product> GetProductsByCategory(string category)
        {
            return products.Where(p => string.Equals(p.Category, category, StringComparison.OrdinalIgnoreCase));
        }


    }


好的代码编写完成:调试。。。。。

那么问题来了:请求的url http://localhost:32873/Products/GetProductById?id=1

居然报了一个404错误

修改地址http://localhost:32873/api/Products/GetProductById?id=1,终于出来了

好换个方法试试:

http://localhost:32873/api/Products/GetAllProducts

抛出异常了,说id不能为空,咋还是GetProductById这个方法呢?我调用的是GetAllProducts这个方法呀,别着急问题终会解决的

app-Start下有一个设置路由的类WebApiConfig.cs

将路由改为以下内容完美运行,

 public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
               name: "DefaultApi",
               routeTemplate: "api/{controller}/{action}/{id}",
               defaults: new { id = RouteParameter.Optional }
           );
            config.Routes.MapHttpRoute(
                name: "Products",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }


            );


            // 取消注释下面的代码行可对具有 IQueryable 或 IQueryable<T> 返回类型的操作启用查询支持。
            // 若要避免处理意外查询或恶意查询,请使用 QueryableAttribute 上的验证设置来验证传入查询。
            


            // 若要在应用程序中禁用跟踪,请注释掉或删除以下代码行
           
            //config.EnableSystemDiagnosticsTracing();
        }
    }


哎终于大功告成了。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值