Search code examples
c#apiwebrequest

Webrequest c# API null once reached the API


I am trying to send a request from server side to my API, here is my code from Server

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();
        }

May API code are below:

[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]);
    }

when my request reach the Action of UserCheck, the value of

([FromBody]User value)

is null

my Class for the User is below

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

BUT once i remove the logonfrom variable from json there is no error, i mean the parameter (value) successfully captures the content i sent.

Thanks


Solution

  • use the following peace of code.

      string json = JsonConvert.SerializeObject(new { username = "afsa", password = "fsaf", system = "fsaf", ip = "fsf", logonfrom ="fsfsd"});