Search code examples
asp.netasp.net-web-apifiddlerasp.net-web-api2

Posting credentials to web API using Fiddler (not Basic Auth)


I've created my first ASP.Net Web API which receives posted credentials and returns a ClaimsPrincipal:

Credentials.vb

Public Class Credentials
    Public Property UserName as String
    Public Property Password as String
End Class

MyController.vb

    <Route("v1/login")>
    <OverrideAuthorization>
    <HttpPost>
    Public Function Login(c as Credentials) As IHttpActionResult
        Dim cp As ClaimsPrincipal = DataBaseLogin.GetDataBasePrincipal(c.UserName, c.Password)
        ' removed for brevity ...
        Return Ok(cp)
    End Function

In Fiddler I am trying to construct a POST to this method:

POST http://localhost:58442/v1/login HTTP/1.1
Host: localhost:58442
Content-type: application/x-www-form-urlencoded
Content-Length: 35

{"Username":"foo","Password":"bar"}

The method is hit (breakpoint trigger break) and variable c is typed as Credential but the values of c.UserName and c.Password in the method are both Nothing.

Update

Solved it. Content-type must be application/json and not application/x-www-form-urlencoded


Solution

  • Basically, because of the simple types (string parameters), Web API is expecting these parameters from the URI and for that reason you are getting 404.

    Change the action method some thing like this (sorry about C#).

    public class MyController : ApiController
    {
        [Route("v1/login")]
        [HttpPost]
        public IHttpActionResult Login(Cred c)
        {
            return Ok();
        }
    }
    
    public class Cred
    {
        public string UserName { get; set; }
        public string Password { get; set; }
    }
    

    Also, include Content-type: application/x-www-form-urlencoded in the request. That should work. BTW, you can use [FromBody] against the string parameter but then you cannot use two, since body can be used only once. In case you have one parameter, you can use that instead of a complex type (class).