c# webapi 開發

來源:互聯網
上載者:User

首先建立一個項目,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();
        }
    }


哎終於大功告成了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.