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", "" }, { "days", }};
var constaints = new RouteValueDictionary { { "areacode", @"0\d{2,3}" }, { "days", @"[1-3]" } };
var dataTokens = new RouteValueDictionary { { "defaultCity", "BeiJing" }, { "defaultDays", } };
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(, , 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 域控制器

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

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 = };
MyHttpClientHandler handler3 = new MyHttpClientHandler { MaxAutomaticRedirections = }; HttpResponseMessage response1 = handler1.SendAsync(request1, new CancellationToken()).Result;
HttpResponseMessage response2 = handler2.SendAsync(request2, new CancellationToken()).Result;
HttpResponseMessage response3 = handler3.SendAsync(request3, new CancellationToken()).Result;
支持自动压缩
asp.net web api 2框架揭秘文摘的更多相关文章
- 感恩回馈,《ASP.NET Web API 2框架揭秘》免费赠送
在继<WCF全面解析(上下册)>.<ASP.NET MVC 4框架揭秘>之后,我的另一本书<ASP.NET Web API 2框架揭秘>( 本书详细信息见< ...
- 《ASP.NET Web API 2框架揭秘》样章(PDF版本)
<ASP.NET Web API 2框架揭秘>(详情请见<新作<ASP.NET Web API 2框架揭秘>正式出版>)以实例演示的方式介绍了很多与ASP.NET ...
- ASP.NET Web API 2框架揭秘
ASP.NET Web API 2框架揭秘(.NET领域再现力作顶级专家精讲微软全新轻量级通信平台) 蒋金楠 著 ISBN 978-7-121-23536-8 2014年7月出版 定价:108.0 ...
- 《ASP.NET Web API 2框架揭秘》
<ASP.NET Web API 2框架揭秘> 基本信息 作者: 蒋金楠 出版社:电子工业出版社 ISBN:9787121235368 上架时间:2014-7-5 出版日期:2014 年7 ...
- 新作《ASP.NET Web API 2框架揭秘》正式出版
我觉得大部分人都是“眼球动物“,他们关注的往往都是目光所及的东西.对于很多软件从业者来说,他们对看得见(具有UI界面)的应用抱有极大的热忱,但是对背后支撑整个应用的服务却显得较为冷漠.如果我们将整个“ ...
- ASP.NET Web API 2 框架揭秘
这不是一本传统意义上的入门书籍 任何 —本书都具有对应的受众群体,所以我不得不将这句话放在最前面,并且希望所有 打算购买此书的读者能够看到.如果你之前对As氵NET W山API(或者AsPNET MⅤ ...
- ASP.NET WEB API 2 框架揭秘 读书笔记(一)
第一章 概述 主要内容是介绍Web的基本概念,Restfull的基本概念及特性.最后介绍创建简单WebApi程序的步骤. Web的基本概念 IP/TCP协议簇分层,分为两种 链路层->网络层-& ...
- ASP.NET Web API 开篇示例介绍
ASP.NET Web API 开篇示例介绍 ASP.NET Web API 对于我这个初学者来说ASP.NET Web API这个框架很陌生又熟悉着. 陌生的是ASP.NET Web API是一个全 ...
- ASP.NET Web API 自定义MediaType实现jsonp跨域调用
代码来自<ASP.NET Web API 2 框架揭秘>一书. 直接上代码: /// <summary> /// 自定义jsonp MediaType /// </sum ...
随机推荐
- POJ 1222 EXTENDED LIGHTS OUT(反转)
EXTENDED LIGHTS OUT Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 12616 Accepted: 8 ...
- LockSupport分析
LockSupport是java.util.concurrent.locks包中的一个工具类,主要提供了一些在创建锁和同步类中用来阻塞其他线程的原始操作. 当有多个线程需要获取同一个资源的锁的时候,如 ...
- line 3: /usr/local/arm/4.3.2/bin/arm-none-linux-gnueabi-gcc: No such file or directory
sudo apt-get install lib32ncurses5(网上下载的很多arm-linux-gcc都是32位的,64位的ubuntu需要按此包)
- java 字符串排序
http://bbs.csdn.net/topics/280032929 大可不需要那样复杂了!(一)如果要排序的为字符串,如:String sortStr = "ACDFE"; ...
- TThread 线程的例子
TThread 线程的例子 D:\Documents\Embarcadero\Studio\14.0\Samples\CPP\RTL\Threads TThread类 该线程类可以完成大多数的线程 ...
- Shiro学习之路 -- 架构及其组件
出自:跟我学shiro 简介 Apache Shiro 是 Java 的一个安全框架.目前,使用 Apache Shiro 的人越来越多,因为它相当简单,对比 Spring Security,可能没有 ...
- win10 IIS 10.0 无法安装 URL Rewrite Module 重写模块
打开注册表 win+R 输入 regidit在HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\InetStp位置 修改注册表 把MajorVersion的值改为9 安装 ...
- 出现The folder is already a source folder
右键build path -> configure build path -> source ,选择 src/main/java.src/test/java删除,然后再新建.
- Color, Material, Lighting
[Color, Material, Lighting] The material and lighting parameters are used to control the built-in ve ...
- Python_09-面向对象编程
目录: 1 面向对象编程1.1 简单例子1.2 调用1.3 python命名规范(约定)1.4 类的设计1.4.1 Exception 异常捕获结构1.4.2 自定 ...