Asp.Net Web Api Getting 401unauthorized code<!-- --> | <!-- -->Patrick Desjardins Blog
Patrick Desjardins Blog
Patrick Desjardins picture from a conference

Asp.Net Web Api Getting 401unauthorized code

Posted on: May 20, 2014

If you are creating a brand new Web Api and try to execute a POST query with Web Api you might receive a 401 status code from the request. This might be because the security of your service is not set correctly. Open the Web Api project (hit F4 when having the project selected from the Solution Explorer).


The second thing that you have to ensure is that you are requesting a json call. This mean that you must have in the request header the content-type set to json.

1User-Agent: Fiddler Host: localhost:17420 Content-Length: 16 Content-Type: application/json

For example, running a post on an action that take a single string require Fiddler to have the Request Header set with the previous 4 lines and the request body of the string desired. For example "This is a test".

1public void Post([FromBody]string value) { }

FiddlerSingleStringPost 400x286

For a more exhaustive test, you can send an object. This require you to use the JSON syntax. The Web Api Controller also requires to have the class defined and the parameter to use this class.

1public void Post([FromBody]DTOExecutionParameters value) { } public class DTOExecutionParameters { public string NameTask { get; set; } public string ParameterName { get; set; } }

WebApiFiddlerPost 400x302

This request has the status 200 and if you set a breakpoint in Visual Studio you can see the values.

PostValueInTheControllerWebApi 400x40