易简.道(ething)

爱在进行时
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

How to Migrate from WCF Web API to ASP.NET Web API

Posted on 2012-03-07 12:15  如是如是  阅读(388)  评论(0编辑  收藏  举报

Introduction

We recently announced that WCF Web API is now ASP.NET Web API. This document provides guidance on how to migrate your existing WCF Web API code to ASP.NET Web API.

Overview

The WCF Web API abstractions map to ASP.NET Web API roughly as follows

WCF Web API

ASP.NET Web API

Service

Web API controller

Operation

Action

Service contract

Not applicable

Endpoint

Not applicable

URI templates

ASP.NET Routing

Message handlers

Same

Formatters

Same

Operation handlers

Filters, model binders

Web API Controllers

Update you service types to be web API controllers by first deriving from ApiController and renaming your service type so that the type name ends with "Controller".

Routing

You can directly map URI templates to routes by defining a route that matches the URI template path and then specifying the method name as the default value for the action route variable. The approach will result in one route per action, which depending on the number of actions may result in significant performance overhead.

To consolidate the number of routes consider refactoring your service so that there is one web API controller per resource.

 Model Binding

Model binding is a powerful feature in ASP.NET MVC (and on its way to Web Forms in ASP.NET 4.5 too). It allows you to write a method that accepts your custom object type as a parameter, and ASP.NET Web API handles mapping posted data to that parameter. It lets you focus on implementing your specifications and get out of the business of mindless (and error prone) mapping code. Here's an example, showing how a method that accepts posted data can focus on the logic of handling the data:

?

1

2

3

4

5

6

7

public HttpResponseMessage<comment> PostComment(Comment comment) 

{

    comment = repository.Add(comment);

    var response = new HttpResponseMessage<comment>(comment, HttpStatusCode.Created);

    response.Headers.Location = new Uri(Request.RequestUri, "/api/comments/" + comment.ID.ToString());

    return response;

}

Filters

Filters are a really powerful feature in ASP.NET MVC. You can use attributes to apply pre/post logic to action methods, entire controllers, or globally to all action methods. They're available in ASP.NET Web API as well, and you use the same kind of logic to both build and apply them. I worked with a sample that applied some custom attribute based validation using a global action filter, and found it really to apply my ASP.NET MVC background.