April 18 2014

Post a simple string value from AngularJS to .NET Web API

UPDATED 10/7/2014: Added more detailed code samples to the end of the post.

I got stuck today trying to post a simple string parameter in the body of an http request from angularjs to a asp.net web api controller, first I was getting a 404 error on the controller route which was fixed by adding the [FromBody] attribute to my parameter like so:

public IHttpActionResult ProcessFile([FromBody]string fileName)

Then I ran into a problem with parameter binding, my fileName parameter kept coming through as null, I tried sending it through as a json object { fileName: 'some file name' } and also just as the name some file name without any luck.

There were a few answers on stack overflow saying to prefix the string with an equals sign or wrap it in a json object with an empty string as the property name like { '': 'some file name' } but both of these approaches seemed a bit hacky to me.

The solution I found was to simply wrap the string value in double quotes in your angular post:

$http.post(Config.apiUrl + '/processfile', '"' + fileName + '"');


Here's a more detailed code sample for the Web API controller and AngularJS service:

Web API Controller

public class ExampleController : ApiController
    public IHttpActionResult ProcessFile([FromBody]string fileName)
        // do something with fileName parameter

        return Ok();

AngularJS Service

'use strict';


.factory('ExampleService', ['$http', 'Config',
    function ($http, Config) {
        var service = {};

        service.ProcessFile = function (fileName) {
            return $http.post(Config.apiUrl + '/example/processfile', '"' + fileName + '"');

        return service;


Sponsored by