Derik Whittaker

Syndication

News


Zero to Self Hosting AspNet WebAPI in a few short steps
Thanks for sharing your feedback! If your feedback doesn't appear right away, please be patient as it may take a few minutes to publish - or longer if the blogger is moderating comments.

So #AspNetWebAPI has finally reach beta and I finally have gotten off my a$$ and starting playing around with it.  Sure I have read the info on line, I have sat through numerous sessions where it was being taught and all along I have been telling myself ‘this stuff kicks ass’ but I just not have not found the time to actually use it or learn it.  That all changed today, and in typically fashion Glenn Block and team have delivered a kick ass, easy as pie solution to a tough issue.  They have managed to take WCF and all of its glory and complication and made it dead simple to use.

This is going to be the first of 2 posts where I will walk you though step by step on how to setup and use the AspNetWebApi in a self hosted situation .  This post will be how to self host the routes/services and the second post will be how to consume the services from a external (non-MVC) application.

Step 1: Create a windows console application

The simplest way to show how to do this is to create a console app, but of course you could have created a winform, wpf or Windows Service but console apps work just great.

One thing to not though is you will want to open up the Properties for your console app and make sure it is using the Full .net 4 framework, not the client profile.  See blow:

image

Step 2: Getting the bits from Nuget to allow self hosting

The simplest way to get and register the bits needed is to fire up Nuget and download them.  If you have not already installed the Nuget bits head over to Nuget.org and download them.

Once you Nuget up and running type in ‘Install-Package' AspNetWebApi.Selfhost’ as shown below.

image

When this is done running you should have the following assemblies added to your solution:

image

Step 3: Setting up a basic route and Setup Self Hosting

In order for your application to be able to host WebApi you will need to setup a basic route and the Self hosting Server. You will want to open up your Program.cs file and add the code below. 

static void Main(string[] args)
{

    var selfHostConfiguraiton = new HttpSelfHostConfiguration( "http://localhost:8080" );
            
    selfHostConfiguraiton.Routes.MapHttpRoute(
        name: "DefaultApiRoute",
        routeTemplate: "endpoints/{controller}",
        defaults: null
        );

    using (var server = new HttpSelfHostServer(selfHostConfiguraiton))
    {

        server.OpenAsync().Wait();

        Console.WriteLine("Hosting at http://localhost:8080/endpoints/{controller}");

        Console.ReadLine();
    }

}

Breaking down the code above.

  1. The first line is where you setup the configuration for the WebApiSelfHost Server.  When setting this up you will need to make sure to put in a valid URL w/ port, if needed.  You may need to use Netsh.exe to register the port if the port you are using is not already setup.
  2. We are creating our default route.  If you have done any Asp.net MVC work this should be confortable for you.  The one difference here is we are using MapHttpRoute rather than MapRoute.  The MapHttproute can be found in System.web.Http namespace
  3. Lastly we are creating and starting our Self host Server.  This is the magic goo.

Step 4: Creating your first controller

Like Asp.net MVC WebApi users a controller to handle inbound requests.  However, we now use ApiController as our base class.  The code below is my basic controller for handing the route I defined above.

public class EpisodeController : ApiController
{
    public IList GetAllEpisodes()
    {
        return new List
                    {
                        new Episode {Id = 1, Name = "Episode 1", ReleasedOn = DateTime.Now.AddDays( -10 )},
                        new Episode {Id = 2, Name = "Episode 2", ReleasedOn = DateTime.Now.AddDays( -5 )},
                        new Episode {Id = 3, Name = "Episode 3", ReleasedOn = DateTime.Now.AddDays( -3 )},
                        new Episode {Id = 4, Name = "Episode 4", ReleasedOn = DateTime.Now.AddDays( 0 )},
                    };
    }
}

Breaking down the code above.

  1. We must inherit from ApiController
  2. If you have done ANY WCF work you will notice that there are ServiceContrace or OperationContract attributes anyplace to be found on the controller….

Step 5: Creating the model to be used by your controller

So we have our controller, now it is time to create the Episode model which is being used by our controller.

public class Episode
{
    public int Id { get; set; }

    public string Name { get; set; }

    public DateTime ReleasedOn { get; set; }
}

Above is our model and if you have done any type of work with WCF you should notice straight away there is NO attributes.  This is awesome Smile

Step 6: Hit F5 and take WebApi For a spin

So we have created the SelfHosting service, we have created our route, we have created our controller and finally we have created out model.  It appears to me we are ready to give this puppy a test ride.

Hit F5 in your project and open up a browser.  Once your browser is up and running navigate to http://localhost:8080/endpoints/episode.

If all goes well you should see something like

image

You may notice this is use XML formatting by default.  If you don’t want xml follow Glenn’s post on how to disable XML formatting.

Till next time,


Posted 02-27-2012 4:42 AM by Derik Whittaker
Filed under: ,

[Advertisement]

Comments

Joey wrote re: Zero to Self Hosting AspNet WebAPI in a few short steps
on 02-27-2012 8:45 AM

If I have IIS, would I ever want to do self host over hosting in ASP.NET?

-

Joey

Derik Whittaker wrote re: Zero to Self Hosting AspNet WebAPI in a few short steps
on 02-28-2012 9:32 AM

@Joey,

I actually self host WCF all the time.  Good cases may be when you already have a server product that and you want to host wcf/webApi inside the existing application.  Another one could be when you do not want to depend on IIS for various reasons.

Greg wrote re: Zero to Self Hosting AspNet WebAPI in a few short steps
on 02-28-2012 9:45 AM

For some reason I get a blank page with this exact example?  Investigating...

AbelebA wrote re: Zero to Self Hosting AspNet WebAPI in a few short steps
on 02-28-2012 11:18 AM

I also get a blank page.  What's up?

Joey wrote re: Zero to Self Hosting AspNet WebAPI in a few short steps
on 02-28-2012 2:37 PM

I was getting errors ... I forgot to install the ASP.NET 4 Beta installer on my desktop. Had it on laptop. Once I did that, the errors and blank pages went away.

Greg wrote re: Zero to Self Hosting AspNet WebAPI in a few short steps
on 02-28-2012 4:33 PM

Same here, was missing the beta.  Works like a charm now!

vurt007 wrote re: Zero to Self Hosting AspNet WebAPI in a few short steps
on 02-28-2012 7:13 PM

exciting possibilities of hosting web api apps outside of IIS .. is it the death of .net / mvc ?

Derik Whittaker wrote WebApi and Json Deserialization into an object model
on 03-01-2012 5:23 PM

If you use WebApi with the Asp.Net MVC framework you may not realize that there is some ‘magic’ that

Fred wrote re: Zero to Self Hosting AspNet WebAPI in a few short steps
on 03-08-2012 5:11 AM

Are there any disadvantages (performance, ...) using self-host instead of IIS? Is it possible to host two web-apps - one using IIS and one using "Self-Host" - on the same port (80)? Only difference should be the url.

Tim Scott wrote re: Zero to Self Hosting AspNet WebAPI in a few short steps
on 03-30-2012 12:29 AM

I tried moving a working IIS hosted APU to self hosted.  No dice.  For starters:

"The type 'System.Web.Routing.Route' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'."

Okay, add a reference.  More fail.  I have this:

GlobalConfiguration.Configuration.ServiceResolver.SetResolver(new StructureMapDependencyResolver(container));

Upon request it complains:

"'MyController' does not have a default constructor."

What, no IoC?  And what about AOP?  I tried this:

GlobalFilters.Filters.Add(new HandleErrorAttribute());

For which I had to reference System.Web.Mvc.  But again, fail:

"Inheritance security rules violated by type: 'System.Web.Mvc.CompareAttribute'. Derived types must either match the security accessibility of the base type or be less accessible."

Did MS screw their AOP story for self hosting by merging with MVC a switching to filters?

Ideas?  Maybe it's not ready for prime time?

Tim Scott wrote re: Zero to Self Hosting AspNet WebAPI in a few short steps
on 03-30-2012 11:32 AM

I found answers to my problems.  The selfHostConfiguration object has methods for setting IoC resolver and adding filters.  Now I'm sorry about anything I may have said about anyone's monther.

About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Subscribe
Google Reader or Homepage

del.icio.us CodeBetter.com Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl CodeBetter.com Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of Devlicio.us
Red-Gate Tools For SQL and .NET

NDepend

SlickEdit
 
SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
LiteAccounting.Com
DevExpress
Fixx
NHibernate Profiler
Unfuddle
Balsamiq Mockups
Scrumy
JetBrains - ReSharper
Umbraco
NServiceBus
RavenDb
Web Sequence Diagrams
Ducksboard<-- NEW Friend!

 



Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers

 

Community Server (Commercial Edition)