2013年7月2日 星期二

初次認識 ASP.net 2012 api 撰寫 MVC架構

首先要先開一個 api的專案




good~! 現在可以開始建立api了

1.首先 要建立MVC架構裡面的 "M"


建立一個 Product.cs 的檔案


上面完成的,就是MVC裡面的「M」 ,Model / 資料模組

2.接下來也就是 MVC裡面的「C」,Controller / 控制器程式


新增ProductController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
//宣告
using System.Net;
using System.Web.Http;
using TESTAPI.Models;
//請參考剛剛製作的Product.cs
//TESTAPI.Controllers
namespace TESTAPI.Controllers
{
    public class ProductController : ApiController 
    //注意要修改ApiController  在標頭要加入using System.Web.Http; 不是using System.Net.Http;
    {
        //
        // GET: /Product/
        Product[] products = new Product[]
        {
          new Product { productId = 1, productName = "Tomato Soup", productCategory = "Groceries", productPrice = 1 }, 
            new Product { productId = 2, productName = "Yo-yo", productCategory = "Toys", productPrice = 3.75M }, 
            new Product { productId = 3, productName = "Hammer", productCategory = "Hardware", productPrice = 16.99M } 
        };
        public IEnumerable<Product> GetAllProducts()
        {
            return products;
        }
        public Product GetProductById(int id)
        {
            var product = products.FirstOrDefault((p) => p.productId == id);
            if (product == null)
            {//找不到產品就會出現例外情況
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            return product;
        }
        //public ActionResult Index()
        //{
        //    return View();
        //}
    }
}
恭喜你已經完成Controller / 控制器程式
接下來來test 看看吧
你可能會出現這個問題
解決問題如下
好了嗎?  來測試一下吧
 打入url =>  " /api/Product"
你是否成功看到xml了呢?
ya~
最後呢
如何設定我的 Web API 只傳回 JSON?
有撰寫過 ASP.NET Web API 的讀者可能會發現,每當使用 Chrome 來瀏覽前面的範例網頁時,都會自動變成 XML 格式,如下:
 ASP.NET Web API 內建支援 JSON 與 XML 兩種輸出格式,並依據瀏覽器端送出的 Accept 標頭自動決定回應的內容格式,不過也因為這點讓有些 Web API新手上路的開發人員來說似乎頗為困擾,如何讓 ASP.NET Web API 強迫回應 JSON 結果,以方便直接用任何瀏覽器都能看見 JSON 的執行結果。
good~
參考文獻:

0 意見:

張貼留言