Fork me on GitHub

从 WebAPI Beta 更新到WebAPI RC

The official word on changes from Beta to RC for Web API-related topics (filtered from the original page).

  • ASP.NET Web API now uses Json.NET for JSON formatting: The default JSON formatter in ASP.NET Web API now uses Json.NET for JSON serialization. Json.NET provides the flexibility and performance required for a modern web framework.
  • Formatter improvements: The methods on MediaTypeFormatter are now public to enable unit testing of custom formatters. A single formatter can now support multiple text encodings. UseBufferedMediaTypeFormatter to implement simple synchronous formatting support.FormatterContext has been removed. To get access to the request from a formatter on the server implement GetPerRequestFormatterInstance.
  • Removed System.Json.dll: Because of the overlap with functionality already in Json.NET the System.Json.dll assembly has been removed.
  • XmlMediaTypeFormatter uses DataContractSerializer by default: The XmlMediaTypeFormatternow uses the DataContractSerializer by default. This means that by default ASP.NET Web API will use the Data Contract programming model for formatting types. You can configure theXmlMediaTypeFormatter to use the XmlSerializer by setting UseXmlSerializer to true.
  • Formatters now always handle the body content: ASP.NET Web API formatters are now used consistently for handling both the request and response content. We have removedIRequestContentReadPolicy. The FormUrlEncodedMediaTypeFormatter class has been updated to use MVC-style model binding, so you can still use model binding infrastructure for handling form data in the request body.
  • HTTP content negotiation decoupled from ObjectContent: Previously in ASP.NET Web API all HTTP content negotiation logic was encapsulated in ObjectContent, which made it difficult to predict when HTTP content negotiation would occur. We have decoupled HTTP content negotiation from ObjectContent and encapsulated it as an IContentNegotiator implementation.ObjectContent now takes a single formatter. You can run HTTP content negotiation whenever you want using the DefaultContentNegotiator implementation to select an appropriate formatter.IFormatterSelector has been removed
  • Removed HttpRequestMessage<T> and HttpResponseMessage<T>: Previously there were two ways to specify a request or response with an ObjectContent instance: you could provide anObjectContent instance directly, or you could use HttpRequestMessage<T> orHttpResponseMessage<T>. Having two ways of doing the same thing complicated request and response handling, so HttpRequestMessage<T> and HttpResponseMessage<T> have been removed. To create content negotiated responses that contain an ObjectContent use the CreateResponse<T>extension methods on the request message. To send a request that contains an ObjectContent use the PostAsync<T> extension methods on HttpClient. Or, use the PostAsJsonAsync<T> andPostAsXmlAsync<T> extension methods to specify a request that will be specifically formatted with as JSON or XML respectively.
  • Simplified action parameter binding: You can now predictably determine whether an action parameter will be bound to the request body. This ensures that the request stream is not unnecessarily consumed. Parameters with simple types by default come from the URL. Parameters with complex types by default come from the body. There can be only one body parameter. You can explicitly specify if a parameter comes from the URL or from the body using the [FromUri] and[FromBody] attributes.
  • Query composition is now implemented as a reusable filter: Previously support for query composition was hard coded into the runtime. Query composition is now implemented as a reusable filter that can be applied as an attribute ([Queryable]) to any action that returns anIQueryable instance. This attribute is now required to enable query composition.
  • Cookies: The HttpRequestMessage and HttpResponseMessage classes expose the HTTP Cookie and Set-Cookie headers as raw strings and not structured classes. This made it cumbersome and error prone to work with cookies in ASP.NET Web API. To fix this we introduced two newCookieHeaderValue and CookieState that follow RFC 6265 HTTP State Management Mechanism. You can use the AddCookies extension method to add a Set-Cookie header to a response message. Use the GetCookies extension method to get all of the CookieHeaderValues from a request.
  • HttpMessageInvoker: The HttpMessageInvoker provides a light weight mechanism to invoke anHttpMessageHandler without the overhead of using HttpClient. Use HttpMessageInvoker for unit testing message handlers and also for invoking message handlers on the server.
  • Response buffering improvements: When web-hosting a web API the response content length is now set intelligently so that responses are not always chunked. Buffering also enables reasonable error messages to be returned when exceptions occur in formatters.
  • Independently control IHttpController selection and activation: Implement theIHttpControllerSelector to control IHttpController selection. Implement IHttpControllerActivator to control IHttpController activation. The IHttpControllerFactory abstraction has been removed.
  • Clearer integration with IoC containers that support scopes: The dependency resolver for ASP.NET Web API now supports creating dependency scopes that can be independently disposed. A dependency scope is created for each request and is used for controller activation. Configuring dependency resolution (i.e. HttpConfiguration.DependencyResolver) is optional and is now configured separately from the default services used by ASP.NET Web API (HttpConfiguration.Services). However, the service locator consults the dependency resolver first for required services and then falls back to explicitly configured services.
  • Improved link generation: The ASP.NET Web API UrlHelper how has convenience methods for generating links based on the configured routes and the request URI.
  • Register resource for disposal at the end of the request life-time: Use the RegisterForDisposeextension method on the request to register an IDisposable instance that should be disposed when the request is disposed.
  • Monitoring and diagnostics: You can enable tracing by providing an ITraceWriterimplementation and configuring it as a service using the dependency resolver. The ILoggerinterface has been removed.
  • Create custom help and test pages: You now can easily build custom help and test pages for your web APIs by using the new IApiExplorer service to get a complete runtime description of your web APIs.
  • Entity Framework based scaffolding for web APIs: Use the Add Controller dialog to quickly scaffold a web API controller based on an Entity Framework based model type.
  • Create unit test projects for Web API projects: You can now easily create a unit test project for a Web API project using the New ASP.NET MVC 4 Project dialog box.
  • Unauthorized requests handled by ASP.NET Web API return 401 Unauthroized: Unauthorized requests handled by ASP.NET Web API now return a standard 401 Unauthorized response instead of redirecting the user agent to a login form so that the response can be handled by an Ajax client.
  • Configuration logic for MVC applications moved under the App_Start directory: The configuration logic For MVC applications has been moved from Global.asax.cs to a set of static classes in the App_Start directory. Routes are registered in RouteConfig.cs. Global MVC filters are registered in FilterConfig.cs. Bundling and minification configuration now lives in BundleConfig.cs.
  • Add Controller to any project folder: You can now right click and select Add Controller from any folder in your MVC project. This gives you more flexibility to organize your controllers however you want, including keeping your MVC and Web API controllers in separate folders.

看到这篇文章Tips for Updating From WebAPI Beta to WebAPI RC,已经很好的总结了 WebAPI Beta 更新到WebAPI RC,特意做下笔记。

1、Nuget Packages : Beta到RC的WebAPI的Nuget Packages的名称发生了改变,现在叫做Microsoft.AspNet.WebApi:

image

2、Dependency Injection:作者用的是Ninject,有篇文章介绍如何设置DependencyResolver:Using Ninject with the latest ASP.NET Web API source,我喜欢用Autofac,可以直接通过Nuget Package更新 Autofac ASP.NET Web API (RC) Integration

3、泛型HttpResponseMessage 已经被替换:beta的代码里用到的new HttpResponseMessage<T>(someValue) 需要改成用Control的Request属性

Request.CreateResponse(HttpStatusCode.OK, result);

4、不再需要自定义JSON.NET formatter,RC的Json.NET目前成为了Web API默认的序列化器,多余的System.Json.dll已经被移除。正如微软所说:

Json.NET为一个现代Web框架提供了灵活性与性能。

    var formatter = GlobalConfiguration.Configuration.Formatters.Where(f =>
           {
               return f.SupportedMediaTypes.Any(v => v.MediaType.Equals("application/json", StringComparison.CurrentCultureIgnoreCase));
           }).FirstOrDefault() as JsonMediaTypeFormatter;
           if (formatter != null)
           {
               formatter.SerializerSettings = new JsonSerializerSettings()
               {
                   NullValueHandling = NullValueHandling.Ignore,
                   Converters = new JsonConverter[] { new IsoDateTimeConverter() }
                   // whatever else you need... 
               };
           }

5、扩展方法GetUserPrincipal已经不存在,你可以用在自定义的Authorize attribute里使用System.Threading.Thread.CurrentPrincipal.Identity,也可以使用ApiController里的属性User。

6、参数绑定器:http://www.cnblogs.com/xiaoweiyu/archive/2012/06/12/2546116.html

posted @ 2012-06-12 08:41  张善友  阅读(3334)  评论(4编辑  收藏  举报