Host ASP.NET Web API In WPF Application
(The following content from CodeEase.com)
Now WCF Web API changed to ASP.NET Web API. ASP.NET Web API has the feature of self-host. In Microsoft official site, they also provides two simples ASP.NET Web API self-host samples. However, they are so simple and actually they looks like the “same” one because these 2 simples are Console applications and use very similar content.
The WPF is more popular for new Windows Application solutions, so we want to find a sample that how to host ASP.NET Web API in a WPF Application. Let’s start:
First, If you have not installed ASP.NET MVC 4 (at present it is still MVC 4 beta), please go to Microsoft ASP.NET website MVC 4 part to download and install it;
After the MVC 4 stuff installed, we can write the code now.
Note: We are using Visual studio 2010.
1: Open Visual Studio 2010 **as Administrator :
**(Note: this step is important, you must open Visual Studio as Administrator because later we need to listen at a particular HTTP address. )
namespace WpfHostWebApiDemo.Models { public class ItemModel { public int ItemID { get; set; } public string ItemName { get; set; } public double ItemValue { get; set; } } }
5: Add a new folder named Controllers, in this folder, add a new Item, specify the template to Web API Controller Class in Web category. Give the name ItemController
Remove all generated code and add the following code into ItemController class:
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Web.Http; using WpfHostWebApiDemo.Models; namespace WpfHostWebApiDemo.Controllers.Controllers { public class ItemController : ApiController { // GET /api/<controller> public IEnumerable<ItemModel> Get() { return new List<ItemModel> { new ItemModel() { ItemID = 1, ItemName = "Item1", ItemValue = 100 }, }; } } }
6: Host service:
Add the windows loaded event in MainWindow, and add host service code, All MainWindow.xaml,cs file code is like the following:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Web.Http.SelfHost; using System.Web.Http; namespace WpfHostWebApiDemo { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { var config = new HttpSelfHostConfiguration("http://localhost:5477"); config.Routes.MapHttpRoute( "API Default", "api/{controller}/{id}", new { id = RouteParameter.Optional }); using (HttpSelfHostServer server = new HttpSelfHostServer(config)) { server.OpenAsync().Wait(); MessageBox.Show("Web API service started."); } } } }
In above code, we listen localhost:5477, which you can change the port number to what port number you like.
7: Compile and Build project:
Now we build the project, we will see at least 5 error messages:
_The type or namespace name 'ApiController' could not be found (are you missing a using directive or an assembly reference?)
The type or namespace name 'SelfHost' does not exist in the namespace 'System.Web.Http' (are you missing an assembly reference?)
The type or namespace name 'HttpSelfHostConfiguration' could not be found (are you missing a using directive or an assembly reference?)
The type or namespace name 'HttpSelfHostServer' could not be found (are you missing a using directive or an assembly reference?)
The type or namespace name 'HttpSelfHostServer' could not be found (are you missing a using directive or an assembly reference?)
_
The reason is current WPF project is based on the target framework ASP.NET Framework 4 Client Profile, which miss some libraries, Just right click the project name in Visual Studio 2010 and select property, and change the target framework to ASP.NET Framework 4.
After you changed the target framework to .NET Framework 4, Visual Studio 2010 will give you a message that the project need to be closed and re-open, but looks seems the Visual Studio 2010 can not re-load the project automatically, so here you should close Visual Studio manually first, and open Visual Studio 2010 as Administrator again, and load our demo project.
(Note: for avoid to re-open Visual Studio, you’d better change Target framework in step 2)
Now let us rebuild the application, we see the old error messages gone, but we get the following new errors:
The type 'System.Web.Routing.RouteCollection' 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'.
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'.
The reason is we still missed a dll file, let’s add reference to System.Web, the version is 4.0
Now rebuild again. the build is OK now!
8: Run the Web API Service:
Click Ctrl + F5, you will see the service started message which we added in code.
Open web browser and input the URL address: **localhost:5477/api/item
**you will see the service content as XML format on the web page:
Now we know the Web API service is working! You can create a client to consume the service now.