Web API系列之三 基本功能實現


Web API系列之二講解了如何搭建一個WebApi的基架,本文主要在其基礎之上實現基本的功能.下面開始逐步操作:

一、配置WebApi的路由-用於配置外部如何訪問內部資源的url的規則

1、添加Global.asax文件

右鍵項目-選擇添加新項

添加成功,修改Global.asax.cs文件,代碼如下:

using System;
using System.Web.Http;

namespace WebApiApp
{
    public class Global : System.Web.HttpApplication
    {

        protected void Application_Start(object sender, EventArgs e)
        {
            //配置WebApi的路由
            GlobalConfiguration.Configuration.Routes.MapHttpRoute(
                name:"default_api",
                routeTemplate: "{controller}/{item}",
                defaults: new { item=RouteParameter.Optional}
            );
        }
    }
}

ok,路由配置完成

 

二、模擬數據倉儲,用於提供測試的數據,代碼如下:

using System.Collections.Generic;
namespace WebApiApp.Models
{
    public static class Storages
    {
        public static IEnumerable<Student> Students { get; set; }

        static Storages()
        {
            Students = new List<Student>
            {
                new Student{Id=1,Name="張1" },
                new Student{Id=2,Name="張2" },
                new Student{Id=3,Name="張3" }
            };
        }
    }
    public class Student
    {
            public int Id { get; set; }
            public string Name { get; set; } 
    }
}

 

三、編寫Api控制器,通過該控制器向外部暴露數據

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using WebApiApp.Models;

namespace WebApiApp.Controllers
{
    /// <summary>
    /// 當前控制器下的所有方法相當於是一個關於學生資源的集合,里面封裝着對學生的所有操作.
    /// </summary>
    public class StudentController:ApiController
    {
        /// <summary>
        /// Get /students/   -return student list
        /// </summary>
        /// <returns></returns>
        public IEnumerable<Student> Get()
        {
            return Storages.Students;
        }

        /// <summary>
        /// Get /students/zhangsan -return entity
        /// </summary>
        /// <returns></returns>
        public Student Get(string name)
        {
            return Storages.Students.FirstOrDefault(w => w.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase));
        }
    }
}

至此基本功能全部實現,現在可以開始運行項目,測試功能.

 

四、測試

向瀏覽器中輸入   項目地址/Student

項目地址/Student?name=張1

ok,說明項目部署成功.

注:服務器端返回xml的原因是:瀏覽器向服務端請求的就是xml數據,如下圖示:

Chrome瀏覽器接收服務器端返回的數據類型默認的優先級是:html>xhtml+xml>xml>webp>所有(前面的類型都沒有的話就所有了咯)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM