ASP.NET Web API(一)

来源:互联网 发布:数据库项目经理的收获 编辑:程序博客网 时间:2024/05/22 00:11

    ASP.NET Web API是微软推出的一个新的用于建立HTTP服务的框架,其官网: https://www.asp.net/web-api,虽然有WCF,但是通过Web API,建立同样的服务更加方便快捷了,对很多应用来说,也是满足需求了。

    1. 使用Web API要求Visual Studio2012以上,MVC4以上,这里使用Visual Studio2013。新建项目,选择"模板"--"Visual C#"-"Web"-"ASP.NET Web应用程序",输入解决方案名称和路径,如下,然后点击"确定":

        

    2. 弹出窗口选择"Web API",选择"确定":

       

    3. 生成项目结构如下:

       

    4. 添加应用需要用的一个数据模型,该数据模型能自动转化为JSON或XML格式,这个由客户端发来的头中Accept来说明需要什么格式。右键单击“Models”,添加一个Class:

using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace iHouseWebAPI.Models{    public class User    {        public Guid Id        {            get;            set;        }        public string userName        {            get;            set;        }        public string userPassword        {            get;            set;        }        public DateTime lastLoginTime        {            get;            set;        }    }}

    5. 新建一个User控制器用户处理HTTP请求:

   

    选择"Web API 2控制器 空",这类控制器继承于ApiController:

    在新疆项目时,生成的ValuesController是一个控制器模板,参考编写UserController:

   

using System;using System.Collections.Generic;using System.Linq;using System.Net;using System.Net.Http;using System.Web.Http;using iHouseWebAPI.Models;namespace iHouseWebAPI.Controllers{    public class UserController : ApiController    {        User[] gUsers = new User[]        {            new User{Id=Guid.NewGuid(), userName="LinJK", userPassword="123456", lastLoginTime=new DateTime()},            new User{Id=Guid.NewGuid(), userName="LJK", userPassword="abcdef", lastLoginTime=new DateTime()}        };        // GET api/values        public IEnumerable<User> GetAllUsers()        {            return gUsers;        }        // GET api/values/5        public User GetUserByName(String name)        {            var mUser = gUsers.FirstOrDefault((user) => string.Equals(user.userName, name, StringComparison.OrdinalIgnoreCase));            if (mUser == null)            {                throw new HttpResponseException(HttpStatusCode.NotFound);            }            return mUser;        }    }}

    6. 如何请求数据:

        在WebApiConfig配置了路由映射规则:

     在官网可以查看更多信息: https://docs.microsoft.com/en-us/aspnet/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api

      7. 运行。 右键单击解决方案名称,调试启动新实例:

         

          启动调试后,默认会打开HomeController页面,不用管,记住端口即可, 且该页面不要关闭:

         

           打开新的浏览器窗口:

          

// 如果是字符串,需要使用key-value形式,否则直接user/xxx即可


0 0