创建Web API应用程序

Web API特性

先进的 HTTP 编程模型: 使用新的强类型的 HTTP 对象模型直接操作 HTTP 请求和响应, 在 HTTP客户端使用相同的编程模型和 HTTP 管道;

支持路由: Web API 完整支持 ASP.NET 路由, 包括路由参数和约束。 此外, 到动作的映射支持约定, 从此将不再需要向类或者方法添加类似于 [HttpPost] 之类的属性;

内容协商: 客户端与服务端可以一起决定 API 返回数据的格式。 默认支持 XML, JSON 以及 Form URL-Encoded 格式, 可以扩展添加自定义格式, 甚至可以替换掉默认的内容协商策略;

模型绑定与验证: 模型绑定器可以轻易地从 HTTP 请求中提取数据并转换成在动作方法中使用的 .Net 对象;

过滤: Web API 支持过滤, 包括总所周知的 [Authorize] 过滤标记, 可以为 Action 添加并插入自定义过滤, 实现认证、异常处理等;

查询聚合: 只要简单的返回 Iqueryable<T> , Web API 将会支持通过 OData 地址约定进行查询;

改进的 Http 细节可测试性: Web API 不是将 HTTP 细节设置到一个静态的 Context 对象上, 而是使用 HttpRequestMessage 和 HttpResponseMessage 实例, 可以使用这些对象的泛型版本为这些 Http 类型添加自定义类型;

改进的依赖反转 (IoC) 支持: Web API 使用 MVC Dependency Resolver 实现的服务定位器模式在不同的场景下来获取实例;

基于代码的配置: Web API 单独使用代码完成配置, 从而保证了配置文件的整洁;

自托管 (Self-Host) : Web API 除了可以托管在 IIS 中, 还可以托管在进程中,依旧可以使用路由以及其它的特性。

Web API配置

1. 添加类

    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }

2. 注册

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }

在Model中添加如下类

    public class Project:Object
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Category { get; set; }
        public decimal Price { get; set; }
    }

在Controllers中添加如下类

 public class ProductsController : ApiController
    {
        private Project[] projects = new Project[] {
            new Project{Id=1,Name="Huitai",Category="People",Price=1.25M},
            new Project{Id=2,Name="Hello",Category="Hello",Price=4.5M},
            new Project{Id=3,Name="ViewSonic",Category="Computer",Price=1500M}
        };
        public IEnumerable<Project> GetAllProducts()
        {
            return this.projects;
        }
        public Project GetProjectById(int id)
        {
            var project = this.projects.FirstOrDefault(p=>p.Id==id);
            if(project==null)
            {
                var resp = new HttpResponseMessage(HttpStatusCode.NotFound);
                throw new HttpResponseException(resp);
            }
            return project;
        }
        /// <summary>
        /// 返回指定类别所有商品
        /// </summary>
        /// <param name="category"></param>
        /// <returns></returns>
        public IEnumerable<Project> GetProductsByCategory(string category)
        {
            return this.projects.Where(p=>string.Equals(p.Category,category,StringComparison.OrdinalIgnoreCase));
        }
    }

添加视图页面

<html>
<head>
    <title>Asp</title>
    <script src="http://www.cnblogs.com/Scripts/jquery-1.7.1.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $.getJSON("api/products/", function (data) {
                $.each(data, function (key, val) {
                    var str = val.Name + ": $" + val.Price;
                    $('<li/>', { html: str }).appendTo($('#products'));
                });
            });
        });
        function find() {
            var id = $("#prodId").val();
            $.getJSON("api/products/" + id,
            function (data) {
                var str = data.Name + ':$ ' + data.Price;
                $("#product").html(str);
            }).fail(function (jqXHR, textStatus, err) {
                $("#product").html("Error:"+err);
            });
        }
    </script>
</head>
<body>
    <div> 
        <h1>All Products</h1> 
        <ul id='products' /> 
    </div> 
    <div> 
        <label for="prodId">ID:</label> 
        <input type="text" id="prodId" size="5"/> 
        <input type="button" value="Search" onclick="find();" /> 
        <p id="product" /> 
    </div> 

</body>
</html>

 

URI                        HTTP Method                        Action
                        /api/products                         GET                         GetAllProducts()
                        /api/products/1                         GET                         GetProductById(1)
                        /api/products?category=hardware                         GET                         GetProductsByCategory("hardware")

 

源码:https://files.cnblogs.com/byzy/MVC4Demo.rar

posted @ 2012-10-30 09:41  bradleydan  阅读(196)  评论(0)    收藏  举报