Tag Archives: POST

WebApi POST needs a little help

Some of my web apps use ASP.Net WebApi Controllers. They work a lot like MVC Controllers but they’re limited to HTTP Verbs such as Get, Post, Put, Delete and instead of returning a View, they return Data formatted as XML or JSON, or they might perform data operations such as INSERT, UPDATE, DELETE. Usually you’d call these via HttpRequest, or AJAX, or whatever you want to use over HTTP, but sometimes I just want to call the ApiControllers directly from an MVC Controller, treating it like a DAL, and just skip the whole HTTP Request thing. (Not sure if that’s kosher, but it works. Let me know if you think calling ApiController methods directly from code is a bad idea).

Anyway, this works pretty good until you call a POST method, which has some standards and handling which, if not obliged, will throw errors when your HTTP Request is found to be null.

I found this article by Peter Provost on Unit Testing of ApiControllers, which addresses this problem and provides a nice solution.

Taking his advice, I wrote a an extension method for ApiController that seems to get me past any errors when calling Post() on my ApiControllers.

        public static void InitializePost(this ApiController controller)
            var config = new HttpConfiguration();            
            var request = new HttpRequestMessage(HttpMethod.Post, "http://MOCKhost/api/MOCKController");
            var route = config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}");
            var routeData = new HttpRouteData(route, new HttpRouteValueDictionary { { "controller", "MOCK" } });
            controller.ControllerContext = new HttpControllerContext(config, routeData, request);
            controller.Request = request;
            controller.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;
            controller.Request.Properties[HttpPropertyKeys.HttpRouteDataKey] = routeData;

Here is an example that shows how to initialize and call a Post method on an ApiController directly. In this case I’m calling it from within an MVC Controller.

  public ActionResult Create(SomeViewModel viewModel)
    var _api = new SomeApiControllerThatCanInsertObjectsIntoDB();
    return RedirectToAction("Index");