ASP.NET MVC Web API is the way to create HTTP services or RESTful services in the Microsoft platform. It supercedes the WCF REST framework. Web API can be accessed by a wide variety of client applications including browsers in desktops, tablets and mobiles. It scales well in the web.

In this post, I have created a Web API for Comments. Create a new MVC application. Create a controller called CommentController which is a API controller with CRUD methods which works with Entity Framework. After adding code for different operations, the CommentController should like the following:

There are methods for GET, GET(1), PUT, POST, DELETE. These methods can be accessed from a browser using a friendly URL like http://localhost:port/api/Comment. The default return value is a JSON array. Using content negotiation in the request header, other types like XML array can be returned.

Next, we can create a WPF application which uses a HTTP client to access the Web API. The WPF application contains a DataGrid which displays all comments in a grid like fashion. The DataGrid is bound to an ObservableCollection<Comment>. Each row contains a Delete button which will delete a comment. There is a Save button for the entire DataGrid. It enumerates through each comment and tries to update the comment using a PUT operation. If the update fails because the comment does not exist, the comment is added to the database using a POST operation. After the comment is added, the ID is updated in the DataGrid.

The XAML code is shown below:

The code for Save operation using HttpClient is shown below:

The method that does the PUT operation is client.PutAsync(). The method that does the POST operation is client.PostAsync(). Overall, the code is very simple to read and is self-explanatory.

The entire project can be found here: CommentApiDemo

Using a WPF client to access MVC Web API
Tagged on:     

Leave a Reply

Your email address will not be published. Required fields are marked *