[c#] HttpWebRequest-The remote server returned an error: (400) Bad Request

I am getting The remote server returned an error: (400) Bad Request error while running the following code. I am trying to upload xml file on the http server. My xml file contains tag for the username,password and domain and when i am trying to connect is manually i am able to connect it,but using same credentials when i am trying to connect it through this code, i am getting 400 Bad Request error. Please suggest me how to overcome this issue. Thanks `

  public static void UploadHttp(string xml)     
    {

        string txtResults = string.Empty;
        try
        {
            string url = "http://my.server.com/upload.aspx ";
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.KeepAlive = false;
            request.SendChunked = true;
            request.AllowAutoRedirect = true;
            request.Method = "Post";
            request.ContentType = "text/xml";
            var encoder = new UTF8Encoding();
            var data = encoder.GetBytes(xml);
            request.ContentLength = data.Length;
            var reqStream = request.GetRequestStream();
            reqStream.Write(data, 0, data.Length);
            reqStream.Close();
            WebResponse response = null;
            response = request.GetResponse();
            var reader = new StreamReader(response.GetResponseStream());
            var str = reader.ReadToEnd();
        }
        catch (WebException ex)
        {
            if (ex.Status == WebExceptionStatus.ProtocolError)
            {
                HttpWebResponse err = ex.Response as HttpWebResponse;
                if (err != null)
                {
                    string htmlResponse = new StreamReader(err.GetResponseStream()).ReadToEnd();
                    txtResults = string.Format("{0} {1}", err.StatusDescription, htmlResponse);
                }
            }
            else
            {

            }
        }
        catch (Exception ex)
        {
            txtResults = ex.ToString();
        }
    }`

This question is related to c# .net upload httpwebrequest

The answer is


What type of authentication do you use? Send the credentials using the properties Ben said before and setup a cookie handler. You already allow redirection, check your webserver if any redirection occurs (NTLM auth does for sure). If there is a redirection you need to store the session which is mostly stored in a session cookie.


400 Bad request Error will be thrown due to incorrect authentication entries.

  1. Check if your API URL is correct or wrong. Don't append or prepend spaces.
  2. Verify that your username and password are valid. Please check any spelling mistake(s) while entering.

Note: Mostly due to Incorrect authentication entries due to spell changes will occur 400 Bad request.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to upload

Upload file to SFTP using PowerShell This application has no explicit mapping for /error Schedule automatic daily upload with FileZilla jQuery AJAX file upload PHP How to find when a web page was last updated Summernote image upload on change event for file input element Multiple files upload in Codeigniter How to upload files on server folder using jsp How do I measure request and response times at once using cURL?

Examples related to httpwebrequest

C# HttpWebRequest The underlying connection was closed: An unexpected error occurred on a send How to properly make a http web GET request Send JSON via POST in C# and Receive the JSON returned? How to create JSON post to api using C# Use C# HttpWebRequest to send json to web service Post form data using HttpWebRequest HttpWebRequest-The remote server returned an error: (400) Bad Request Get host domain from URL? How to ignore the certificate check when ssl Receiving JSON data back from HTTP request