You are on page 1of 26

Web API 1.

0
By
Amareswara Rao
Implement a Web API
Content negotiation is the process by which a response
format is selected for a given response when there are
multiple representations available. Content negotiation
can happen multiple ways, but the primary way it
happens is via the HttpRequest header

If no Accept header value is indicated, a request defaults


to JSON.
Raw server request

Raw server response


Actions and parameters to
handle data binding
You can use simple types (such as int, string, bool,
DateTime, and so forth) or complex types.

Simple types are filled with data from your URL. This
means that you can pass a property such as id by putting it
in the URL and making sure that routing knows about it.

Complex types are read from the message body using a


media-type formatter. This is a key principle of HTTP:
Resources are sent in the message body. Content
negotiation enables you to convert the message body to the
correct type and use it in your code.
FromUri

public HttpResponseMessage Get([FromUri] Person person) {/


* implementation */}

http://localhost/api/Persons/?FirstName=John&LastName=Doe

FromBody

public HttpResponseMessage Get([FromBody] Person person) {/


* implementation */}

http://localhost/api/Persons/
Using HttpMessageHandler
Message handler : An incoming request is matched to a
route and then sent to a specific Web API controller.

These method handlers are chained together and are called


when a request comes in and when the response is returned to
the client.

Where message handlers can be used ?

You dont want to add logging or authentication code to each


and every action method. Instead, you want to define this in
one single place and then attach the code to each request.
In webconfig class

config.MessageHandlers.Add(new LoggingMessageHandler());

If we want to apply message handler for specific route, then


Implementing dependency
injection
Single responsibility principle

Open/closed principle

Liskov substitution principle

Interface segregation principle

Dependency inversion principle


Dependency injection is a method following the last
principle: dependency inversion.

Dependency inversion states that your code shouldnt


depend on concrete objects but upon abstractions.

Why?

Because it creates code that is less coupled and, as such, is


easier to maintain.
This code uses a concrete class, WebClient, to get the
content of microsoft.com. But what if you want to change
this code to retrieve the data from a cache? Because you are
programming against a concrete class, you have to change
each and every line of code that uses WebClient.

Now, what if you dont depend upon a concrete class, but an


abstraction instead? Lets say you have the following
interface
This interface doesnt reveal anything about its
implementation. You dont know whether it uses a
WebClient, Entity Framework, XML file, or some other
kind of magic to load the content. You can now create
an implementation that uses WebClient

But how do you get this class into your Web API controller? You
could add a constructor like this:
But this still couples your class to a concrete
implementation, although in a dierent place. Instead,
you can use dependency injection, meaning that you ask
for the objects you need, and they are injected into your
class at construction. You do this by first changing your
constructor:
To help the Web API framework, create the class and resolve all
dependencies you need to implement an interface called
IDependencyResolver. This class is used by Web API to create
objects that have dependencies, such as the ContentController.
config.DependencyResolver = new ResolveController();

Tools to implement dependency injections is : Unity

Use Nuget to install this package.


Action filters and Exception
filters
This attribute can be applied to a method to force it to return
XML. This completely replaces the default behavior of content
negotiation, and its something you should only use in special
circumstances. In this case, I once used this code to return XML to
a client who expected XML but didnt use the correct Accept
header.

You can apply a filter to a controller or a method by placing the


attribute above the method or class definition.

You can also apply an attribute globally by adding it to


HttpConfiguration.Filters. This can be useful when you have an
attribute, such as a RequireHttps attribute, that should be used in
all requests.
Implementing asynchronous
and synchronous actions
The code you normally see is synchronous. It runs from
top to bottom and executes your statements one at a
time. When looking at a piece of code, you cant predict
how long things will take. Some operations, such as
incrementing an integer, can execute very quickly. Other
operations, such as calling an external web service or
database, can potentially take a long time.
Because your web server has a limited amount of threads to
service incoming requests, you want to use your threads wisely.
Making a thread wait for an external call to come back is a waste
of resources. This is where asynchronous code can help you.
When you make an asynchronous call to an external dependency,
such as a database or a file, the thread is immediately returned so
it can serve other incoming requests. When the external call
finishes, an available thread is used to process the remainder of
the request.

you can improve the scalability of your service dramatically. Please


be aware however, both for the exam and on the job, that you
should use asynchronous calls only for I/O-bound operations.
Using it on CPU-bound operations is a waste of resources on your
server. Because CPU-bound operations require a thread to
process, an asynchronous call would just pick a dierent thread
and then switch back to another thread when it finishes.
Streaming Actions

When working with Web API, you will definitely


encounter a situation in which you want to return a
large amount of data. Maybe you need to return a lot of
data from a database or binary data.

You might also like