C# WinApp throws (403) Fobidden exception while sending HTTP/GET request

1k Views Asked by At

I have ASP.NET website. When I call the url 'http://example.org/worktodo.ashx' from browser it works ok.

I have created one android app and if I call the above url from android app then also it works ok.

I have created windows app in C# and if I call the above url from that windows app then it fails with error 403 forbidden.

Following is the C# code.

        try
        {
            bool TEST_LOCAL = false;
            //
            //  One way to call the url
            //
            WebClient client = new WebClient();
            string url = TEST_LOCAL ? "http://localhost:1805/webfolder/worktodo.ashx" : "http://example.org/worktodo.ashx";
            string status = client.DownloadString(url);
            MessageBox.Show(status, "WebClient Response");

            //
            //  Another way to call the url
            // 
            WebRequest request = WebRequest.Create(url);
            request.Method = "GET";
            request.Headers.Add("Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
            request.Headers.Add("Connection:keep-alive");
            request.Headers.Add("User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36");
            request.Headers.Add("Upgrade-Insecure-Requests:1");
            request.Headers.Add("Accept-Encoding:gzip, deflate, sdch");
            request.ContentType = "text/json";
            WebResponse response = request.GetResponse();

            string responseString = new System.IO.StreamReader(response.GetResponseStream()).ReadToEnd();
            MessageBox.Show(responseString, "WebRequest Response");
        }
        catch (WebException ex)
        {
            string error = ex.Status.ToString();

        }

The exception thrown is:

        The remote server returned an error: (403) Forbidden.
        StatusCode value is 'Forbidden'
        StatusDescription value is 'ModSecurity Action'

Following is android app code (uses org.apache.http library):

    Handler handler = new Handler() {
        Context ctx = context;  // save context for use inside handleMessage()
        @SuppressWarnings("deprecation")
        public void handleMessage(Message message) {
            switch (message.what) {
                case HttpConnection.DID_START: {
                    break;
                }
                case HttpConnection.DID_SUCCEED: {
                    String response = (String) message.obj;
                    JSONObject jobjdata = null;
                    try {
                        JSONObject jobj = new JSONObject(response);
                        jobjdata = jobj.getJSONObject("data");
                        String status = URLDecoder.decode(jobjdata.getString("status"));
                        Toast.makeText(ctx, status, Toast.LENGTH_LONG).show();
                    } catch (Exception e1) {
                        Toast.makeText(ctx, "Unexpected error encountered", Toast.LENGTH_LONG).show();
                        // e1.printStackTrace();
                    }
                }
            }
        }
    };

    final ArrayList<NameValuePair> params1 = new ArrayList<NameValuePair>();
    if (RUN_LOCALLY)
        new HttpConnection(handler).post(LOCAL_URL, params1);
    else
        new HttpConnection(handler).post(WEB_URL, params1);
}

Efforts / Research done so far to solve the issue:

I found following solutions that fixed 403 forbidden error for them but that could not fix my problem

  1. Someone said, the file needs to have appropriate 'rwx' permissions set, so, I set 'rwx' permissions for the file
  2. Someone said, specifying USER-AGENT worked, I tried (ref. Another way to call)
  3. Someone said, valid header fixed it - used Fiddler to find valid header to be set, I used Chrome / Developer Tools and set valid header (ref. another way to call)
  4. Someone configured ModSecurity to fix it, but, I don't have ModSecurity installed for my website, so, not an option for me
  5. Many were having problem with MVC and fixed it, but, I don't use MVC, so those solutions are not for me
  6. ModSecurity Reference manual says, to remove it from a website, add <modules><remove name="ModSecurityIIS" /></modules> to web.config. I did but couldn't fix the issue

My questions are:

  1. Why C# WinApp fails where as Android App succeeds?
  2. Why Android App doesn't encounter 'ModSecurity Action' exception?
  3. Why C# WinApp encounter 'ModSecurity Action' exception?
  4. How to fix C# code?

Please help me solve the issue. Thank you all.

1

There are 1 best solutions below

0
On

I found the answer. Below is the code that works as expected.

    bool TEST_LOCAL = false;
    string url = TEST_LOCAL ? "http://localhost:1805/webfolder/worktodo.ashx" : "http://example.org/worktodo.ashx";

    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
    request.Method = "GET";
    request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
    request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36";
    request.ContentType = "text/json";

    WebResponse response = request.GetResponse();
    string responseString = new System.IO.StreamReader(response.GetResponseStream()).ReadToEnd();
    MessageBox.Show(responseString, "WebRequest Response");

NOTE: requires using System.Net;