使用Fiddler(非Basic Auth)将凭据发布到Web API

时间:2014-08-12 16:05:07

标签: asp.net asp.net-web-api fiddler asp.net-web-api2

我创建了我的第一个ASP.Net Web API,它接收发布的凭据并返回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

在Fiddler中,我正在尝试为此方法构建POST

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"}

方法被命中(断点触发中断),变量c被输入为Credential,但方法中c.UserNamec.Password的值均为{{1} }}

更新

解决了它。 Nothing必须为Content-type而非application/json

1 个答案:

答案 0 :(得分:2)

基本上,由于简单类型(字符串参数),Web API期望从URI中获取这些参数,因此您获得404。

更改动作方法有点像这样(抱歉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; }
}

此外,请在请求中添加Content-type: application/x-www-form-urlencoded。这应该工作。顺便说一下,你可以对字符串参数使用[FromBody]但是你不能使用两个,因为body只能使用一次。如果您有一个参数,则可以使用该参数而不是复杂类型(类)。

相关问题