asp.net web api 2框架揭秘文摘

第一章 概述

URI 统一资源标识符

URL 统一资源定位符

http方法:get,post,put,delete,head等

状态码:100-199,请求已被接受;

           200-299,成功状态;

           300-399,重定向;

           400-499,客户端错误;

           500-599,服务端错误;

restful web api:roa,面向资源

特征:

1.采用URI标识资源

2.使用“链接”关联相关的资源

3.使用统一的接口

4.使用标准的HTTP方法

5.表示多种资源表示方式

6.无状态性

soap web service: rpc,面向功能

第二章 路由

2.1 asp.net 路由

2.1.1 请求URL与物理文件的分离

 var defaults = new RouteValueDictionary { { "name", "*" }, { "id", "*" } };
            RouteTable.Routes.MapPageRoute("", "employees/{name}/{id}","~/default.aspx", true, defaults);

 

2.1.4 注册路由映射

   var defaults = new RouteValueDictionary { { "areacode", "010" }, { "days", 2 }};
            var constaints = new RouteValueDictionary { { "areacode", @"0\d{2,3}" }, { "days", @"[1-3]" } };
            var dataTokens = new RouteValueDictionary { { "defaultCity", "BeiJing" }, { "defaultDays", 2 } };

            RouteTable.Routes.MapPageRoute("default", "{areacode}/{days}","~/weather.aspx", false, defaults, constaints, dataTokens);
            var constaints = new RouteValueDictionary { { "areacode", @"0\d{2,3}" }, { "days", @"[1-3]{1}" }, { "httpMethod", new HttpMethodConstraint("POST") } };

 2.2 ASP.NET Web api 路由

具有自己的路由系统

第三章 消息处理管道

3.1 httpmessagehandler 管道 delegatinghandler,httpserver

3.2 web host 模式下的消息处理管道(asp.net 管道)

3.3 self  host 模式下的消息处理管道 httpbinging  httpselfhostserver

第四章 HttpController的**

ApiController httpcontrollerdescriptor

第五章 Action的选择

httpactiondescriptor httpparameterdescriptor

第六章 特性路由

RouteAttribute

为路由变量设置约束

设置URI前缀,RoutePrefix

第七章 Model绑定(上篇)

1. 基于HttpRouteData的参数绑定

MODEL绑定机制来对目标Action的某个参数进行绑定。

   [ModelBinder]
    [DataContract(Namespace = "http://www.artech.com/")]
    public class DemoModel
    {
        [DataMember]
        public int X { get; set; }

        [DataMember]
        public int Y { get; set; }

        [DataMember]
        public int Z { get; set; }
    }
   [HttpGet]
        [Route("action1/{x}/{y}/{z}")]
        public DemoModel Action1(int x, int y, int z)
        {
            return new DemoModel { X = x, Y = y, Z = z };
        }

        [HttpGet]
        [Route("action2/{x}/{y}/{z}")]
        public DemoModel Action2(DemoModel model)
        {
            return model;
        }

        [HttpGet]
        [Route("action3/{x}/{y}/{z}")]
        public IEnumerable<DemoModel> Action3(DemoModel model1, DemoModel model2)
        {
            yield return model1;
            yield return model2;
        }

        [HttpGet]
        [Route("action4/{model1.x}/{model1.y}/{model1.z}/{model2.x}/{model2.y}/{model2.z}")]
        public IEnumerable<DemoModel> Action4(DemoModel model1, DemoModel model2)
        {
            yield return model1;
            yield return model2;
        }

2.基于查询字符串的参数绑定

第八章 Model绑定(下篇)

简单类型,复杂类型

集合,数组,字典绑定

第九章 参数的绑定

5个原生的httpparameterbinging:

1.ModelBinderParameterBinding

2. FormatterParameterBinding

FormUrlEncodedMediaTypeFormatter

  <script>
        $(function () {
            $("form").submit(function () {
                $.ajax({
                    url: "http://localhost:3721/api/contacts",
                    type: "POST",
                    contentType: "application/x-www-form-urlencoded",
                    data: $("form").serialize()
                });
                return false;
            });
        });
    </script>
   public void Post()
        {
            IEnumerable<MediaTypeFormatter> formatters = new MediaTypeFormatter[] { new FormUrlEncodedMediaTypeFormatter() };
            FormDataCollection formData = this.Request.Content.ReadAsAsync<FormDataCollection>(formatters).Result;
            foreach (var item in formData)
            {
                Console.WriteLine("{0,-12}: {1}", item.Key, item.Value);
            }
        }

JQueryMvcFormUrlEncodedFormatter :兼容任意类型

  IEnumerable<MediaTypeFormatter> formatters = new MediaTypeFormatter[] { new JQueryMvcFormUrlEncodedFormatter() };
            Contact contact = this.Request.Content.ReadAsAsync<Contact>(formatters).Result;

3. HttpRequestParameterBinding

4.CancellationTokenParameterBinding

5.ErrorParameterBinding

第十章 参数的验证

10.1 几种参数验证方式

1. 手工验证绑定的参数(不推荐)

2. 使用ValidationAttribute特性

  public class Person
    {
        [Required(ErrorMessageResourceName = "Required",ErrorMessageResourceType = typeof(Resources))]
        public string Name { get; set; }

        [Required(ErrorMessageResourceName = "Required",ErrorMessageResourceType = typeof(Resources))]
        [Domain("M", "F", "m", "f", ErrorMessageResourceName = "Domain",ErrorMessageResourceType = typeof(Resources))]
        public string Gender { get; set; }

        [Required(ErrorMessageResourceName = "Required",ErrorMessageResourceType = typeof(Resources))]
        [Range(18, 25, ErrorMessageResourceName = "Range",ErrorMessageResourceType = typeof(Resources))]
        public int? Age { get; set; }
    }

验证结果的自动响应:

   public class ValidateAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (!actionContext.ModelState.IsValid)
            {
                actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
            }
            base.OnActionExecuting(actionContext);
        }
    }

第十一章 Action的执行

第十二章 过滤器

5种Filter类型:

AuthenticationFilter 认证

AuthorizationFilter 授权

ActionFilter 回调操作

利用自定义actionfilter实现对action方法执行结果的缓存(S1207)

ExceptionFilter 异常处理

OverrideFilter 屏蔽外层注册的Filter

第十三章 安全

1. iis/asp.net认证:

basic 认证:明文传输,不安全  (弹出windows登录界面)

digest 认证:只适合domain模式,不适合work group模式;哈希算法(md5)(弹出windows登录界面)

Windows集成认证(AD局域网),(不弹出windows登录界面):利用NTLM和kerberos协议

ntlm:nt lan manager 域控制器 

asp.net web api 2框架揭秘文摘

kerberos:包含客户端,服务端**分发中心。kdc

asp.net web api 2框架揭秘文摘

Forms认证(web)

2. ssl/tls 非对称加密:

a.(消息的发送方采用公钥进行加密,接收方采用私钥进行解密)。

b. 数字签名(hash)。签名和检验。

    数字证书(ca:认证权威机构)(是一种数字签名的声明)

    微软提供的MakeCert.exe ;也可以利用IIS创建一个自我签名的证书,设置绑定端口

    webapi使用HTTPS,

    public override void OnAuthorization(HttpActionContext actionContext)
        {
            //如果当前为HTTPS请求,授权通过
            if (actionContext.Request.RequestUri.Scheme == Uri.UriSchemeHttps)
            {
                base.OnAuthorization(actionContext);
                return;
            }

            //对于HTTP-GET请求,将Scheme替换成https进行重定向
            if (actionContext.Request.Method == HttpMethod.Get)
            {
                Uri requestUri = actionContext.Request.RequestUri;
                string location = string.Format("https://{0}/{1}", requestUri.Host, requestUri.LocalPath.TrimStart('/'));
                IHttpActionResult actionResult = new RedirectResult(new Uri(location), actionContext.Request);
                actionContext.Response = actionResult.ExecuteAsync(new CancellationToken()).Result;
                return;
            }

            //采用其他HTTP方法的请求被视为Bad Request
            actionContext.Response = new HttpResponseMessage(HttpStatusCode.BadRequest)
            {
                ReasonPhrase = "SSL Required"
            };
        }

3.第三方认证:oauth2.0。安全令牌:access token。4种授权模式:1.implicit   2.authrization code 3.resource owner password credentials 4. client credential

第十四章 跨域资源共享

1.JSONP

2.采用ASP.NET WebApi 原生的机制实现跨域资源

第十五章 web api的调用

两种调用方式:

一种是ajax,一种是HttpClient

   HttpRequestMessage request1 = new HttpRequestMessage(HttpMethod.Get, "http://localhost:3721/api/demo/action1");
            HttpRequestMessage request2 = new HttpRequestMessage(HttpMethod.Get, "http://localhost:3721/api/demo/action1");
            HttpRequestMessage request3 = new HttpRequestMessage(HttpMethod.Get, "http://localhost:3721/api/demo/action1");

            MyHttpClientHandler handler1 = new MyHttpClientHandler { AllowAutoRedirect = false, AutomaticDecompression = System.Net.DecompressionMethods.GZip };
            MyHttpClientHandler handler2 = new MyHttpClientHandler { MaxAutomaticRedirections = 1 };
            MyHttpClientHandler handler3 = new MyHttpClientHandler { MaxAutomaticRedirections = 2 };

            HttpResponseMessage response1 = handler1.SendAsync(request1, new CancellationToken()).Result;
            HttpResponseMessage response2 = handler2.SendAsync(request2, new CancellationToken()).Result;
            HttpResponseMessage response3 = handler3.SendAsync(request3, new CancellationToken()).Result;

支持自动压缩