MVC4 Quick Tip #4–Updating a model the HTTP way with ASP.Net Web API

by ely March 18, 2012 15:50

Disclaimer: This code is based on MVC 4 Beta 1, and might change in future releases.

The www.asp.net/web-api website has a few good videos and decent examples, however, I didn’t notice a concrete way of doing an update using ASP.Net Web API.  So I thought I would quickly document how I implemented it for anyone else looking how to do so, and will welcome any comments or suggestions if I am going about this the wrong way.

ASP.Net Web API embraces HTTP and all that comes along with it, and that is one of the main differences between APIControllers and the regular controllers found in MVC.  In MVC, you would normally do all your CUD (Create, Update, Delete) through POST actions to the controller.  In ASP.Net Web API, the recommended way is to use the POST verb for creating objects, PUT for updating objects, and DELETE (you guessed it) for deleting objects.  So instead of having a controller decorated with HTTP Verbs attributes, APIControllers uses a convention in the way you name your methods.  If the method begins with Get, it must be a get request, Post, a create request,and so on.

Below is a quick example of doing a PUT request to an APIController.  Your update logic will undoubtedly   vary, but it is the outline of the method that is important:

   1:  public HttpResponseMessage<Person> PutPerson(Person person)
   2:          {
   3:              _repo.Attach(person);
   4:              _unitOfWork.Commit();
   5:              var response = new HttpResponseMessage<Person>(person, HttpStatusCode.OK);
   6:              response.Headers.Location = new Uri(Request.RequestUri, "/api/person/" + person.Id);
   7:              return response;
   8:          } 

The jQuery AJAX call for this method is as follows:

   1:  $.ajax("/api/person", {
   2:              data: person,
   3:              type: "PUT",
   4:              contentType: "application/json",
   5:              statusCode: {
   6:                  200: function (data) {
   7:                      //success
   8:                  },
   9:                  500: function (data) {
  10:                      //error
  11:                  }
  12:              }
  13:          });

Tags:

mvc

MVC4 Quick Tip #3–Removing the XML Formatter from ASP.Net Web API

by ely March 05, 2012 14:09

ASP.Net Web API provides a powerful new feature called content negotiation that will automatically format of your requests based on what the client asks for.  For instance, if the client sends ‘application/xml’ in the Content-Type HTTP header, then the format of your response will be XML.  The two default formatters included in Web API are the XML formatter, and the JSON formatter. The beauty of the automatic content negotiation is that you don’t need to write any code to map your models into these formats, it is taken care of for you by the formatters.  You can even create your own formatters to serve up different types as well, such as images, vCards, iCals, etc.

If all you are doing with your Web API is serving up JSON to either web or mobile clients, you might not feel the need to offer up any other format besides JSON.  This might also be helpful for quickly testing your APIs when hitting them with a web browser as some browsers send application/xml as their default content type.

Disclaimer: This code is based on MVC 4 Beta 1, and might change in future releases.

To remove the XML formatter is really easy, and I found this tip from Glenn Block, who conveniently posted this to his blog while I was searching for a way to do this.  In order to do so, put the following code somewhere in your Application_Start method in the global.asax.cs file:

GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear()

Tags:

mvc

MVC4 Quick Tip #2–Use Delegates to setup the Dependency Resolver instead of creating a Dependency Resolver class

by ely February 20, 2012 15:29

I’m a big fan of cutting out unneeded or unnecessary code, so here is a tip that isn’t new in MVC4, but I just discovered it and thought it was really cool and worth sharing.  When using IOC in MVC, you setup a class that implements IDependencyResolver, which has methods to return services for a given type.  While these classes where simple, it always seemed like a bit of ceremony was required whenever starting up a new MVC app.

The following example shows what a DependencyResolver class looks like using my favorite IOC framework, Ninject:

   1:  public class NinjectDependencyResolver : IDependencyResolver
   2:      {
   3:          private readonly IKernel _kernel;
   4:   
   5:          public NinjectDependencyResolver(IKernel kernel)
   6:          {
   7:              _kernel = kernel;
   8:          }
   9:   
  10:          public object GetService(Type serviceType)
  11:          {
  12:              return _kernel.TryGet(serviceType);
  13:          }
  14:   
  15:          public IEnumerable<object> GetServices(Type serviceType)
  16:          {
  17:              return _kernel.GetAll(serviceType);
  18:          }
  19:      }

Nothing terribly complicated, but a lot of fluff.

I saw in a demo in last week’s C4MVC talk, that the DependencyResolver that was setup to create the APIController classes had some overrides I never saw before, and low and behold, the standard MVC DependencyResolver also has these overrides:

ioc

So instead of providing the SetResolver method with a DependencyResolver class, you can just provide it two delegate methods that would normally be in the DependencyResolver (GetService, and GetServices):

   1:  DependencyResolver.SetResolver(
   2:                  x => kernel.TryGet(x),
   3:                  x => kernel.GetAll(x));

POW!  Cut that 20+ line class down to a method that takes two parameters.  BAM!

Tags:

mvc

MVC4 Quick Tip #1–Put your API Controllers in a different folder to avoid class naming collisions

by ely February 20, 2012 15:23

This post is the start of a series of quick tips for Asp.Net MVC 4, which was released in beta form last week.  You can find out more about MVC4 and download the beta from www.asp.net/mvc/mvc4.

Disclaimer: This code is based on MVC 4 Beta 1, and might change in future releases.

MVC 4 ships with the new Asp.net Web APIs, which allow you to create RESTful services from within your web projects (Web Forms or MVC).  In previous versions of MVC, people commonly used Controllers to return JSON to front end websites and other clients.  While this worked for many scenarios, it was difficult to create services that were truly RESTful in nature, taking advantage of all that HTTP had to offer.

With Web APIs, you can now create “API” Controllers.  While these controllers don’t require you to follow REST, their default behavior encourages you to do so.

When starting up a new MVC 4 project, you might be tempted to put new API Controllers in the same folder  (or more accurately, namespace) as your MVC Controllers.  While this will work, you are limited in that you cannot have two classes with the same name in the same namespace.  It will be a common scenario when you have a MVC Controller with the same name as a API Controller.  For instance, you can have a MVC AccountController to serve views for Accounts in your system, and an API AccountController to respond to XHR requests from your website (or mobile devices, other services, etc..).  One way I have found to get around this limitation is to put your API Controllers in a folder called API (or whatever folder/namespace you wish), like so:

controller

Default routes in MVC 4 will respond to MVC controllers with the route of /{controller},  and the default API route will respond to routes of /api/{controller}.  Since the AccountsController in the API folder inherits from APIController, it is okay that you have two classes named AccountsController in your project, the routing engine will know to use the correct one in the API folder.

Tags:

mvc

Global Filters and Dependency Injection in MVC3

by ely August 18, 2011 01:07

I’ve been struggling with finding a good solution to resolve dependencies in global filters lately.  Since it does not appear that global filters are created through the FilterAttributeFilterProvider (I don’t get any results back from base.GetFilters, hit me up if I’m doing something wrong here), my global filters that had resolve attributes on its properties were never being created by the provider, and thus, not getting those properties resolved.

It then dawned on me that the global filters are actually being instantiated in the global.asax.cs file (or wherever your app startup exists at).  So instead of newing up the object directly, I just let Ninject do it for me:

private static void RegisterGlobalFilters(GlobalFilterCollection filters, IKernel kernel)
        {
            filters.Add(new HandleErrorAttribute());
            filters.Add(kernel.TryGet(typeof(UserProviderFilterAttribute)));
        }

At first this felt like a giant hack, but after awhile I warmed up to it and realized that since this is the area of responsibility for creating global filters, that using Ninject to resolve its dependencies does in fact belong here.

If you have other methods for doing resolving your dependencies in global filters, or if I am way off base, I would love to hear any comments or suggestions.

Tags: ,

mvc

String Extension Methods in Razor

by ely January 08, 2011 17:16

The new Razor view engine contains several handy extension methods you can use in your views.  These methods mostly deal with either detecting if a string value can be converted to a particular type, or converting string values to a particular type.  For instance, the following code checks to see if a querystring value is a decimal, and if so, to format it as a currency:


@{
    if (Request.QueryString["amount"].IsDecimal())
    {
        @Request.QueryString["amount"].AsDecimal().ToString("c")W
    }
    else
    {
        @: Amount is not a valid number
    }
}

There are Is(Type), and As(Type) methods for bools, datetimes, decimals, floats, and ints. All of the As(Type) conversion methods take in an optional second parameter that can serve as the default value in case the conversion is not successful.

These extension methods are handy and can save some time and lines of code when dealing with strings.  They are in the System.Web.WebPages namespace, which new projects in MVC3 and Webmatrix automatically reference, so you do not need to worry about adding any using statements into your views in order to take advantage of them.  If you want to take advantage of them in your views, you can simply add a using statement to System.Web.WebPages.

Tags:

mvc | razor

Demo from my MVC/EF/jQuery Talk

by ely August 26, 2010 16:45

Sorry this is a few days late, but I have finally uploaded my demo from my talk at last Monday’s Denver Visual Studio.Net User Group

If you were there, thanks for coming out and seeing our community launch event for Visual Studio 2010.  We had a packed house of 100+ people, and had a great time.

In order to run this demo, you will need the Entity Framework Code First CTP4 binaries.  See Scott Guthrie’s post about EF4 code first and info on how to download it

Tags:

.Net | jQuery | VS2010 | mvc | entity framework

Powered by BlogEngine.NET 2.0.0.36
Theme by Mads Kristensen | Modified by Mooglegiant

About me

@ElyLucas

I am a Denver based software developer, focusing mainly on web technologies in the Microsoft stack.  I dig Asp.Net, MVC, jQuery, C#, JavaScript, and HTML5.  I am starting to dabble in mobile technologies like iOS, Android, and wp7, and have particular interests in mobile web.  I am a Microsoft MVP for Asp.Net/IIS.  I live in Westminster, CO with my wife, son, and dog.  During the day, I sling code for @aspenware creating awesome software.


Month List

Page List

Site hosted by: