Httpwebrequest Asp.net returning 400 error

Asked

Viewed 879 times

0

I’m making an appointment at a api to receive a token access, using the Postman, the options Body and Raw, passing the access data in the body, everything works fine, but in my example I have the error:

An Exception of type 'System.Net.Webexception' occurred in System.dll but was not handled in user code Additional information: Remote server returned an error: (400) Incorrect Request.

public string ConsultarUsuario(string url)
{

    var request = (HttpWebRequest)WebRequest.Create(url);
    var postData = "{ username:sistema, password:senha }";
    var data = Encoding.ASCII.GetBytes(postData);

    request.Method = "POST";
    request.ContentType = "raw";
    //  request.ContentType = "application/json";
    // request.ContentType = "application/x-www-form-urlencoded";
    request.ContentLength = data.Length;

    using (var stream = request.GetRequestStream())
    {
          stream.Write(data, 0, data.Length);
    }
    var response = (HttpWebResponse)request.GetResponse();
    var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
            return responseString;
}

1 answer

1

The way to do it would be:

        public string ConsultaUsuario(string url)
        {
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.ContentType = "application/json";
            request.Method = "POST";

            using (var streamWriter = new StreamWriter(request.GetRequestStream()))
            {
                string json = new JavaScriptSerializer().Serialize(new
                {
                    username = "login",
                    password = "senha"
                });

                streamWriter.Write(json);
            }

            var response = (HttpWebResponse)request.GetResponse();
            using (var streamReader = new StreamReader(response.GetResponseStream()))
            {
                return streamReader.ReadToEnd();
            }

        }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.