您的位置:首页 > 其它

WebApi学习笔记

2016-05-01 22:24 302 查看
1、与mvc区别:
(1)controller继承自ApiController
(2)action不返回视图而是返回数据
(3)访问:http://localhost:1671/api/products/(productscontroller)

2、浏览器访问结果区别
(1)火狐、谷歌返回xml
(2)IE返回json包
原因:出现这种差别的原因是IE和Firefox发送了不同的Accept报头,因此,Web API在响应中发送了不同的内容类型

3、解决循环引用
(1)App_Start文件夹,并打开名为WebApiConfig.cs的文件
// 新代码:把JSON格式化器设置为防止对象引用,并把XML格式化器从管线(指HTTP的请求处理管线)中完全删除
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);

4、Authorization
(1)MVC和Web API都定义了Authorize注解属性,但位于不同的命名空间。MVC使用的是System.Web.Mvc.AuthorizeAttribute,而Web API使用System.Web.Http.AuthorizeAttribute

5、Knockout.js
(1)是一个JavaScript库,它让HTML控件很容易与数据进行绑定。Knockout.js使用的是“模型-视图-视图模型(MVVM)”模式

6、ApiExplorer类
(1)为Web API创建帮助页面
(2)vs2013需要引用System.Net.Http 4.0.0.0 并在Areas/view/web.config中修改: <add assembly="System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

7、通过.NET客户端调用Web API
(1)安装Web API客户端库:通过NuGet :Install the Web API Client Libraries
(2)创建一个新的HttpClient实例
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:9000/");

// 为JSON格式添加一个Accept报头
client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json"));
(3)具体CURD操作:http://www.cnblogs.com/r01cn/archive/2012/11/20/2779011.html
(4)// 列出所有产品
HttpResponseMessage response = client.GetAsync("api/products").Result; // Blocking call(阻塞调用)!
//采用Result属性的过程是应用程序线程阻塞的。控制台应用程序的阻塞没问题,但是,你决不应该在一个Windows应用程序的UI上做这种事,因为这会阻塞UI去响应用户的输入

8、HttpClient消息处理器
(1)在客户端,HttpClient类使用消息处理器处理请求。默认的处理器是HttpClientHandler,它在网络上发送请求,并从服务器获取响应。你可以把自定义消息处理器插入到这种客户端管线之中.
(2)要编写自定义消息处理器,需从System.Net.Http.DelegatingHandler进行派生,并重写SendAsync方法
class MessageHandler1 : DelegatingHandler
{
private int _count = 0;
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
_count++;
request.Headers.Add("X-Custom-Header", _count.ToString());
return base.SendAsync(request, cancellationToken);
}
}
(3)要将自定义处理器添加到HttpClient,需使用HttpClientFactory.Create方法:HttpClient client = HttpClientFactory.Create(new Handler1(), new Handler2(), new Handler3());
(4)要在服务器端添加消息处理器,需要将该处理器添加到HttpConfiguration.MessageHandlers集合。如果创建项目用的是“ASP.NET MVC 4 Web应用程序”模板,你可以在WebApiConfig类中做这件事:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "Route2",
routeTemplate: "api2/{controller}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: null,
handler: new MessageHandler2() // per-route message handler(单路由消息处理器)
);

config.MessageHandlers.Add(new MessageHandler1()); // global message handler(全局消息处理器)
}
}
(5)具体参见:http://www.cnblogs.com/r01cn/archive/2012/11/22/2781707.html

9、WebApi路由
(1)Web API的默认路由模板是“api/{controller}/{id}”。在这个模板中,“api”是一个文字式路径片段,而{controller}和{id}则是占位符变量.
(2)/api/contacts
/api/contacts/1
/api/products/gizmo1
(3)路由变异
替代用于HTTP方法的命名约定,可以明确地为一个动作指定HTTP方法,这是通过以HttpGet、HttpPut、HttpPost或HttpDelete注解属性对动作方法进行修饰来实现的.
(4)具体参见:http://www.cnblogs.com/r01cn/archive/2012/11/23/2784224.html

10、ASP.NET Web API中的异常处理
(1)异常过滤器实现System.Web.Http.Filters.IExceptionFilter接口。编写异常过滤器最简单的方式是通过System.Web.Http.Filters.ExceptionFilterAttribute类进行派生,并重写其OnException方法.
(2)以下是将NotImplementedException(没有实现接口或抽象类要求的方法时,出现的异常)异常转换成HTTP状态码“501 — 未实现”的一个过滤器:
public class NotImplExceptionFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
if (context.Exception is NotImplementedException)
{
context.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented);
}
}
}
(3) 使用方式:
[NotImplExceptionFilter]
public Contact GetContact(int id)

[NotImplExceptionFilter]
public class ProductsController : ApiController

public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Filters.Add(new ProductStore.NotImplExceptionFilterAttribute());

// Other configuration code(其它配置代码)...
}
}
(4)具体参见:http://www.cnblogs.com/r01cn/archive/2012/12/04/2801664.html

11、ASP.NET Web API批处理器(不太了解)

12、ASP.NET Web API中的HTTP Cookie
(1)具体参见:http://www.cnblogs.com/r01cn/archive/2013/05/16/3081108.html

13、媒体格式化器(JSON和XML)
(1)可以自定义返回的数据格式
(2)具体参见:http://www.cnblogs.com/r01cn/archive/2013/05/17/3083400.html

14、ASP.NET Web API中的JSON和XML序列化
(1)参见:http://www.cnblogs.com/r01cn/p/3155653.html

15、模型验证
(1)参见:http://www.cnblogs.com/r01cn/p/3193095.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: