request:
POST /api/login/login HTTP/1.1
Host: localhost:8998
Connection: keep-alive
Content-Length: 27
Accept: application/json, text/javascript, */*; q=0.01
Origin: http://localhost:8998
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Referer: http://localhost:8998/HtmlPage1.html
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9
username=roger&password=123
server code:
[RoutePrefix("api/login")]
public class LoginController : ApiController
{
public static Dictionary<string, string> Users = new Dictionary<string, string> { { "roger", "123" }, { "apple", "321" } };
[AcceptVerbs("POST")]
[Route("login")]
public string Login(User user)
{
var o = this;
if (Users.ContainsKey(user.UserName))
{
if (user.Password == Users[user.UserName])
{
return user.ToString();
}
}
return "invalid username or password";
}
}
public class User
{
public string UserName{ get; set; }
public string Password{ get; set; }
public override string ToString()
{
return UserName + "@" + Password;
}
}
注意事项:
正确的User类:
public class User
{
public string UserName{ get; set; }
public string Password{ get; set; }
}
错误的User类:
public class User
{
public string UserName;
public string Password;
}
- User类必须使用property,不可以使用field,后者导致不能正确反序列化,Login函数接收不到正确的参数
- application/json无此事项
- 公共成员变量使用property包装,不要偷懒