The remote server returned an error: (401) Unauthorized. RRS feed

  • Question

  • User-1312778766 posted

    net.4 web forms
    membership and authorization.

    i am trying to get response between 2 pages on the same domain.

    tried to use webClient and HttpWebResponse.

    on both cases i get
    The remote server returned an error: (401) Unauthorized.

    have to say that for some reason its do works with ajax call.

    on the root web.config

    <authentication mode="Forms">
          <forms loginUrl="~/Account/Login" defaultUrl="~/" timeout="6000" protection="All" slidingExpiration="true"/>
        <profile defaultProvider="SqlProfileProvider">
            <add name="SqlProfileProvider" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="LocalSqlServer" applicationName="/"/>
            <!--              passwordFormat="clear"              -->
            <add connectionStringName="LocalSqlServer" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="true" maxInvalidPasswordAttempts="50" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" name="AspNetSqlMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
        <roleManager enabled="true">
            <add connectionStringName="LocalSqlServer" applicationName="/" name="SqlRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
            <add name="Access-Control-Allow-Headers" value="accept, content-type"/>
            <add name="Access-Control-Allow-Origin" value="*"/>
            <add name="Access-Control-Allow-Methods" value="POST, GET, OPTIONS"/>
          <remove fileExtension=".json"/>
          <mimeMap fileExtension=".json" mimeType="text/plain"/>
          <remove fileExtension=".appcache"/>
          <mimeMap fileExtension=".appcache" mimeType="text/plain"/>
        <modules runAllManagedModulesForAllRequests="true"/>

    web config on directories 

          <deny users="?" /> <<--- without the ? its working!

     public static void PostData(string sUrl, KeyValuePair<string, string>[] oKeyValuePair)
                #region use that fun like that
                //string r = U.PATH.ToAbsoluteUrl("~/Content/shop/TEST/xxxxxxxx/zzz.aspx");
                //Dictionary<string, string> dic = new Dictionary<string, string>();
                //dic.Add("theKey1", "theValue1");
                //dic.Add("theKey2", "theValue2");
                //U.WEBCALL.PostData(r, dic.ToArray());
                StringBuilder sbParams = new StringBuilder();
                for (int i = 0; i < oKeyValuePair.Length; i++)
                    if (i < oKeyValuePair.Length - 1)
                StreamWriter writer = null;
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(sUrl);
                webRequest.Method = "POST";
                webRequest.ContentType = "application/x-www-form-urlencoded";
                webRequest.ContentLength = sbParams.ToString().Length;
                webRequest.Timeout = 20000; //A request that didn't get respond within 20 seconds is unacceptable, and we would rather just retry.
                webRequest.KeepAlive = false;
                webRequest.ProtocolVersion = HttpVersion.Version10;
                webRequest.ServicePoint.Expect100Continue = false;
                ServicePointManager.DefaultConnectionLimit = 1000;
                    writer = new StreamWriter(webRequest.GetRequestStream());
                catch (WebException e1) {
                    if (writer != null)
            public static string[] webPost(string sUrl, Dictionary<string, string> sPostParametersDic = null)
                string[] sReturnVal = new string[3];
                string sPostData = "";
                if (sPostParametersDic != null)
                    foreach (string key in sPostParametersDic.Keys)
                        sPostData += HttpUtility.UrlEncode(key) + "="
                              + HttpUtility.UrlEncode(sPostParametersDic[key]) + "&";
                // Create a request using a URL that can receive a post. 
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(sUrl);
                string un = "admin1", pswrd = "admin1admin1!";
                var cache = new CredentialCache();
                cache.Add(new Uri(sUrl), "Digest", new NetworkCredential(pswrd, un));
                req.Credentials = cache;//  new NetworkCredential(un, pswrd);
                //buildCredentials(sUrl, un, pswrd, "TMG:BASIC");
                //req.CookieContainer =GetAuthCookies(sUrl, un, pswrd);
                //req.PreAuthenticate = true;
                string cre = String.Format("{0}:{1}", un, pswrd);
                byte[] bytes = Encoding.ASCII.GetBytes(cre);
                string base64 = Convert.ToBase64String(bytes);
                req.Headers.Add(HttpRequestHeader.Authorization, "basic " + base64);
                req.Headers.Add(HttpRequestHeader.ContentEncoding, "utf-8");
                req.KeepAlive = false;
                // Set the Method property of the request to POST.
                req.Method = "POST";
                // Create POST data and convert it to a byte array.
                //string sPostData = "This is a test that posts this string to a Web server.";
                byte[] byteArray = Encoding.UTF8.GetBytes(sPostData);
                // Set the ContentType property of the WebRequest.
                req.ContentType = "application/x-www-form-urlencoded";
                // Set the ContentLength property of the WebRequest.
                req.ContentLength = byteArray.Length;
                req.UseDefaultCredentials = true;
                req.PreAuthenticate = true;
                req.Credentials = CredentialCache.DefaultCredentials;
                // Get the request stream.
                Stream dataStream = req.GetRequestStream();
                // Write the data to the request stream.
                dataStream.Write(byteArray, 0, byteArray.Length);
                // Close the Stream object.
                    // Get the response.
                    using (var res = (HttpWebResponse)req.GetResponse())
                        var head = res.Headers.ToString();
                        sReturnVal[0] = res.StatusCode.ToString();
                        // Display the status.
                        sReturnVal[1] = res.StatusDescription;
                        // Get the stream containing content returned by the server.
                        dataStream = res.GetResponseStream();
                        // Open the stream using a StreamReader for easy access.
                        using (StreamReader reader = new StreamReader(dataStream))
                            // Read the content.
                            string responseFromServer = reader.ReadToEnd();
                            // Display the content.
                            sReturnVal[2] = responseFromServer;
                            // Clean up the streams.
                catch (Exception e)
                    sReturnVal[1] = e.Message;
                return sReturnVal;
     private void try1()
                var client = new WebClient { Credentials = new NetworkCredential(un, pw) };
                client.UseDefaultCredentials = true;
                var response = client.DownloadString(thePath);
                write("try1-func", response);
            catch (Exception s)
                write("try1-err", s.Message);

    each user have 2 roles.

    thank you

    Sunday, May 21, 2017 3:28 PM

All replies

  • User-2057865890 posted

    Hi 2xo1,

    The remote server returned an error: (401) Unauthorized.

    If your request needs to be authenicated, then you will need to send the client credentials with the request.

    <deny users="?" /> <<--- without the ? its working!

    It denies access to the anonymous user. A good blog entry discussing this topic can be found at: Guru Sarkar's Blog.

    Best Regards,


    Monday, May 22, 2017 7:31 AM
  • User-1312778766 posted

    ya look on the functions.. 

    i do send heather with the username password and domain before constructing the request body,

    and all non root web.config only asking to be login member (without roles restrictions)

    there for i dont understand why i get 401!

    from ajax call its work... but not from server...

    Monday, May 22, 2017 9:32 AM
  • User1967761114 posted

    Hi 2xo1,

    According to your code, it seems like has some errors .

    I rewrite the method of WebPost, and test succeed, you could refer to the following code:

    public string[] WebPost(string url, Dictionary<string, string> postParams)
         StringBuilder postData = new StringBuilder();
         foreach (var item in postParams)
             if (postData.Length > 0)
             postData.Append(item.Key + "=" + HttpUtility.UrlEncode(item.Value));
         ASCIIEncoding ascii = new ASCIIEncoding();
         byte[] postBytes = ascii.GetBytes(postData.ToString());
         //bulild request
         var webRequest = (HttpWebRequest)WebRequest.Create(url);
         webRequest.Method = "POST";
         webRequest.ContentType = "application/x-www-form-urlencoded";
         webRequest.ContentLength = postBytes.Length;
         webRequest.Credentials = new NetworkCredential("username", "password");
         //push data into requeststream
         using (Stream postStream = webRequest.GetRequestStream())
             postStream.Write(postBytes, 0, postBytes.Length);
         //send request and then get response stream
         string[] sReturnVal = new string[3];
         using (var response = (HttpWebResponse)webRequest.GetResponse())
             sReturnVal[0] = response.StatusCode.ToString();
             sReturnVal[1] = response.StatusDescription;
             using (var httpStreamReader = new StreamReader(response.GetResponseStream()))
                  //read result
                  sReturnVal[2] = httpStreamReader.ReadToEnd();
         return sReturnVal;

    If you have any other questions, please feel free to contact me any time.

    Best Regards



    Saturday, May 27, 2017 7:26 AM