我正在尝试从服务器端向我的API发送请求,这是我的服务器代码
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:59606/api/values/UserCheck");
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"username\":\"User\"," +
"\"password\":\"Mypassword\"," +
"\"logonfrom\":\"DOMAIN\\DomainName\"}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
Console.WriteLine(result);
Console.ReadLine();
}
可能的API代码如下:
[HttpPost]
[ActionName("UserCheck")]
public bool UserCheck([FromBody]User value)
{
ContextType CT = ContextType.Domain;
if (value.logonfrom.Split('\\')[0] == "DOMAIN")
{
CT = ContextType.Domain;
}else if(value.logonfrom.Split('\\')[0] == "MACHINE")
{
CT = ContextType.Machine;
}else
{
return false;
}
return CheckCredentials(value.username, value.password, CT,value.logonfrom.Split('\\')[1]);
}
当我的请求到达UserCheck的Action时,
的值([FromBody]User value)
为空
我的用户类位于
之下public class User
{
public string username { get; set; }
public string password { get; set; }
public string system { get; set; }
public string IP { get; set; }
public string logonfrom { get; set; }
}
但是一旦我从json中删除了 logonfrom 变量,就没有错误,我的意思是参数(值)成功捕获了我发送的内容。
由于
答案 0 :(得分:0)
使用以下代码安静。
string json = JsonConvert.SerializeObject(new { username = "afsa", password = "fsaf", system = "fsaf", ip = "fsf", logonfrom ="fsfsd"});