ASP.NET Web API 学习 一

Technorati 标记: ASP.NET Web API

 

从参加工作开始就开始关注博客园,在园子里学到很多知识,看过很大大牛的文章,确从未发表过一个字。最近刚刚换了公司,学习Web API,就此开始我的第一篇文章吧,也作为学习的记录!

简介就不多介绍,说说我对ASP.NET Web API 的一点点理解。

不同于 Web Service、WCF, ASP.NET Web API 直接访问和处理 Http 请求和响应,在开发中,减少了很多工作,让人感觉一切是如此顺畅。

首先,创建一个 ASP.NET MVC 4 Web Application

2015-07-01_173823

选择 Web API

2015-06-29_134843

创建成功后,会默认生成一个示例。

public class ValuesController : ApiController
{
        // GET api/values
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/values/5
        public string Get(int id)
        {
            return "value";
        }

        // POST api/values
        public void Post([FromBody]string value)
        {
        }

        // PUT api/values/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/values/5
        public void Delete(int id)
        {
        }
}

我这里是偷了个懒,直接使用了 NorthWind 数据库,从网上下载一个 NorthWind 数据库还原到本地的 SQL Server 中,然后新建一个 ADO.NET Entity Data Model

image

选择 Generate from database,Next

image

点击 New Connection

image

选择本地数据库,输入用户名密码,选中 NORTHWIND,测试连接成功,OK

image

选择Yes (会生成一个App.Config文件,成功之后,要把里面 NORTHWINDEntities 的 connectionStrings 拷到 Web 项目的 WebConfig 中),点击 Next

image

选中Tables,Finish

image

 

在 Models中 Add 一个新的 Class, Employee

2015-07-01_175056

从 edmx 文件的 Employee类里,把属性拷出来

image

public class Employee
{
        public int EmployeeID { get; set; }
        public string LastName { get; set; }
        public string FirstName { get; set; }
        public string Title { get; set; }
        public string TitleOfCourtesy { get; set; }
        public Nullable<System.DateTime> BirthDate { get; set; }
        public Nullable<System.DateTime> HireDate { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        public string Region { get; set; }
        public string PostalCode { get; set; }
        public string Country { get; set; }
        public string HomePhone { get; set; }
        public string Extension { get; set; }
        public byte[] Photo { get; set; }
        public string Notes { get; set; }
        public Nullable<int> ReportsTo { get; set; }
        public string PhotoPath { get; set; }
}

我使用了AutoMapper 将 DTO 转化为 Model,如果没有的可以使用 NuGet 下载一个

使用方法参考:https://github.com/AutoMapper/AutoMapper/wiki

image

之后打开 Global.asax.cs,添加 Mapper 方法,这样在 Controller 中,就可以直接转化了。

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    WebApiConfig.Register(GlobalConfiguration.Configuration);
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
        
    Mapper();
}

private void Mapper()
{
    //model to dto
    AutoMapper.Mapper.CreateMap<DX.MVCWebAPI.Models.Employee, DX.DataAccess.Employee>();

    //dto to model
    AutoMapper.Mapper.CreateMap<DX.DataAccess.Employee, DX.MVCWebAPI.Models.Employee>();
}

保存好之后,创建一个 Controller,EmployeesController

2015-07-01_094118

添加下面的方法,AutoMapper 可以直接将 DTO 的集合换位 Model 的集合

public IEnumerable<Models.Employee> GetAllEmployees()
{
var list = new List<Models.Employee>();
    using (var context = new NORTHWNDEntities())
    {
list = AutoMapper.Mapper.Map<System.Data.Entity.DbSet<DataAccess.Employee>, List<Models.Employee>>(context.Employees);
    }
return list.ToArray();
}

最后在Views/Home 里增加一个新的View, Employee,记得在HomeController 里增加Action

image

Employee View 页面代码

<div id="body">
    <input type="button" id="getAll" value="GetAll" />
    <div id="employeeAll">
    </div>
    <script src="~/Scripts/jquery-1.8.2.min.js"></script>
    <script type="text/ecmascript">
        $().ready(function () {
            $("#getAll").click(function () {
                $.getJSON("/api/v1/Employees")
                    .done(function (data) {
                        var html = "<ul>";
                        $(data).each(function (i, item) {
                            html += "<li>" + item.EmployeeID + " | " + item.LastName + " " + item.FirstName + " | " + item.Title + "</li>";
                        });
                        html += "</ul>";
                        $("#employeeAll").html(html);
                    });
            });
        });
    </script>
</div>

执行程序,点击 GetAll,大功告成。

2015-07-01_170637

 

有不对的地方,欢迎大家指出。

 

作为一名苦逼的程序猿,谨以此记录成长路上的点点滴滴。

转载于:https://www.cnblogs.com/daxiong105/p/4614291.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值