request.querystring not found in static method

20,972

Solution 1

You do not have HttpContext.Current in your static method, because your static method has no current context.

It should work, when your static method is executed on a thread that is executing a Http request. To get around this limitation you should supply HttpContext.Current.Request.QueryString as a parameter to your static function form PageLoad event or where ever you are in your request life-cycle.

Solution 2

You have to pass the query string along with the call. this can be achieved from your ajax call.

   var qString = "?" + window.location.href.split("?")[1];
      $.ajax({ 
              url: "<aspx pagename>/<ajax method>" + qString,
              data: {},
              dataType: "json",
              contentType: "application/json; charset=utf-8",
              type: "POST",
              success: function(){},
              error: function () { },
              completed: function () { }
             });

Then server side variables can be accessed as normal.

string value = HttpContext.Current.Request.QueryString["itemId"].ToString();

Solution 3

int itemid =Convert.ToInt32(HttpContext.Current.Request.Form["itemid"]);

Solution 4

You only need to pass the query string as a parameter into the method of WebService.

Share:
20,972
Rajaram Shelar
Author by

Rajaram Shelar

I am a software developer, a Microsoft certified technology specialist. Like web development specially using C#/Asp.Net/MVC/Jquery/AWS/Microservices/DynamoDB. Love freelancing and knowledge sharing.

Updated on December 07, 2021

Comments

  • Rajaram Shelar
    Rajaram Shelar over 2 years

    I have static method in which I want to extract querystring value of the request. But it gives me null value when i am calling it from webmethod. Below is the some code

    public static int GetLatestAssetId()
        {
            int itemid=0;
            if (HttpContext.Current.Request.QueryString["itemId"] != null)
            itemid = Convert.ToInt32(HttpContext.Current.Request.QueryString["itemId"]);
            return itemid;
        }
    
    [WebMethod]
    
            public static string GetContactData()
            {
    
                GetLatestAssetId();
                return "Success"
            }
    

    I am calling this webmethod from the ajax call.It works fine in page load but not in static method. How do I use this in static method. Please assist.