Home » WebServices » WebApi » Asp.Net Web Api Getting 401unauthorized code

Asp.Net Web Api Getting 401unauthorized code

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).

PropertyForWebApiProject

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.

User-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”.

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

FiddlerSingleStringPost

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.

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

WebApiFiddlerPost

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

PostValueInTheControllerWebApi

If you like my article, think to buy my annual book, professionally edited by a proofreader. directly from me or on Amazon. I also wrote a TypeScript book called Holistic TypeScript

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.