4

I'm making a simple asp.net app that displays data which can be filtered based on a few different parameters. As such, the different filters that are currently selected need to be saved somewhere. I'm fairly new to .NET, and am wondering the best way to save this information. I noticed a coworker used Request.QueryString in conjunction with the Sessions dictionary. Something like this on page load:

protected void Page_Load(object sender, EventArgs e) 
{
    if (Request.QueryString["Category"] != null &&
        Request.QueryString["Value"] != null)
    {
        string Category = Request.QueryString["Category"];
        string CategoryValue = Request.QueryString["Value"];

        // selectedFacets is the server side dictionary
        selectedFacets.Add(Category, CategoryValue);                    
    }
 }

The QueryString here is changed when the user presses a button on the webpage, updating the URL.

My question is why even bother with the QueryString at all when all we're using it for is saving a value server side anyway? Wouldn't just making the button an asp controller be easier, something like:

protected void exampleCatexampleVal_Button_onClick(object sender, EventArgs e) 
{
     selectedFacets.Add(exampleCat, exampleVal);
}

Similar business goes on the with the Sessions dictionary: it's just used to save a bunch of values to variables on the server, so why use it in the first place? I'm sure there's a good reason, but right now they just seems overly complicated for what they do. Thank you!

Jacob
  • 3,598
  • 4
  • 35
  • 56
akowalz
  • 359
  • 3
  • 16
  • There is not enough information to answer your question. Why you do not ask your coworker? – Win Jun 27 '13 at 16:30
  • What other information would you need? He's not available, I just have his code to work with. – akowalz Jun 27 '13 at 16:33
  • SessionState is good for security; on the other hand, QueryString is good for SEO and bookmarking. Other than that, we do not how your application works. – Win Jun 27 '13 at 16:36
  • It's pretty hard to answer your question really. Data from the client will be in querystring or Posted. The data has to get to the server. Once on the server, why store it in a server variable vs session (not sure what you mean by server variable here)? That really depends on what you're using that dictionary for. – Mike C. Jun 27 '13 at 16:39
  • Ok, seems the consensus is that it's very context-dependent. What I meant by a server-side variable is something like selectedFacets in my case above. It's a property of the class of the page, just a variable in the code behind the webpage. That seems like a more logical place to store the data than the sessions hash to me, I'm trying to figure out why Sessions and QueryString are so commonplace when saving the values directly seems more straightforward. @MikeC. – akowalz Jun 27 '13 at 16:53

4 Answers4

10

Based on your code examples, I understand that you're talking about ASP.NET WebForms. Your use case is not complete, but I'll show here some alternatives to achieve your goal. If you give further information, I'll gladly update my answer.

Before we get to it, let me just put things clear: HTTP is stateless. Understanding this basic rule is very important. It means that your server will receive a request, send it to your app (and the .NET process), get the resulting page (and assets) and send it back to the client (mostly, a browser). End of story. (Almost) Everything that you've created to respond to the request will be lost. And that's why we have options on where to store objects/values across requests.

Server-side Session

This is one of the easiest options. You simply call this.Session.Add("key", object) and it's done. Let's dig into it:

  • It will use server resources. That is, the most you use the session, the most memory (and other resources, as needed) your app will consume.
  • It will be harder to scale, because data will be on your server memory. Vertical scale may be an option, according to your hardware, but horizontal scale will be limited. You can use a session-server or store session on a SQL Server database, but it won't be so efficient anymore.
  • It's attached to your client session. It will be lost if the user opens another browser or sends a link to his friend.
  • It's relatively safe. I say relatively because of the options below. At least it's server side.

GET arguments (AKA QueryString)

That's another option, and you know it already. You can send data back and forth using the querystring (?that=stuff&on=the&URL=youKnow).

  • It's limited to 2000 characters and that must be serializable. That's why you probably won't put a DataGrid there.
  • The user may change it. Be aware! Always sanitize data from the QueryString.
  • User is free to bookmark the link or send it to a friend and stuff will be the same. That's nice, mind you.

ViewState

You may have heard about it, it's the engine that makes WebForms so lovely (and so hateful). By default, each controller on your page will have its state serialized to the viewstate, which is a huge hidden field with encrypted data on your page. Go on, click "View source" and look for it. Don't scream, please. You may add arbitrary data to the ViewState just like the Session.

  • It's on the client side. Don't trust it.
  • It will be send back and forth on each request, so it will consume extra bandwidth.
  • It will take time to be deserialized/serialized on each request/response.
  • Data must be serializable (you know what I mean).

So, by now I hope that you have enough information to make your own decision. If I missed anything, please let me know.

Community
  • 1
  • 1
Andre Calil
  • 7,652
  • 34
  • 41
  • Wow, thank you for the detailed response. I think the piece of info I needed was that things not in the sessions hash or QueryString won't persist between page loads _at all_. I didn't realize that; making that distinction definitely cleared things up. – akowalz Jun 27 '13 at 17:37
  • 1
    @akowalz Glad to see that you know the differences now. Let me know if you have any further question – Andre Calil Jun 27 '13 at 17:39
2

Have a look at this MSDN Article first. I read through it, and it may answer your question for you.

http://msdn.microsoft.com/en-us/magazine/cc300437.aspx

What you're missing, is how the asp.net page lifecycle works:

http://msdn.microsoft.com/en-us/library/ms178472(v=vs.100).aspx

The thing is, that 'server variable' won't persist between postbacks (AFAIK). It's only useful inside that page, right then. As soon as the page is disposed at the end of the cycle, that dictionary is gone. So you have to store it somewhere if you want to use it later. The article I referenced shows you all the places that you can store information to persist it and where you store it depends on how long you need it to persist, and how many users should have access to it.

Now, certainly, if you DON'T want to persist that dictionary, then sure, just store it the page variable. That's just fine. There's no reason to persist data that you never need again.

Mike C.
  • 3,024
  • 2
  • 21
  • 18
1

It's always good to keep in mind that there is a slight performance hit when storing and retrieving session state from database or from separate process service (StateServer). If session state is stored in-memory, you cannot scale your application to a web farm and this wastes valueable memory in the web server.

On the other hand, using query string values won't waste your memory and resources, it is fast and you don't have to think about managing session state. It gives SEO benefit and allows bookmarks/favorites.

However, you can store only limited amount of data using query string (WWW FAQs: What is the maximum length of a URL). It can also pose a security risk, if sensitive data is exposed or a malicious user tries to find a bug in your code that mishandles URL values. SQL injection attack is one scenario. What you can do is encrypt sensitive values.

Overall there are many aspects to consider here.

Ilkka
  • 306
  • 1
  • 7
0

One of the benefits of using query string values is if you need bookmarks/favorites stored in your application that would allow a user to directly navigate to a page and have certain values be passed into the page without the assistance of an in-memory cache. Take the following for example:

I have a product page that displays a grid view of products that can be filtered by a category name. If I use the categoryId value in the query string, then I can make a bookmark to this page and then later click on the bookmark and the page will work as I left it earlier. Depending upon in-memory cache, that may or may not be there, would not guarantee that my bookmark would work every time.

Karl Anderson
  • 34,606
  • 12
  • 65
  • 80
  • Ok, that makes sense. It seems though that there isn't TOO big of a different, and it's largely personal preference/whatever seems to make sense at the time? – akowalz Jun 27 '13 at 16:40
  • I would not go as far as to say it is personal preference, more like the right tool for the right job. If persisting data across pages or sessions, then query strings are extremely useful; whereas if you are saving a choice on a page (like sort order of ascending or descending on a grid), then session cache is a good candidate for that as you do not care about it once the user logs off of the system. – Karl Anderson Jun 27 '13 at 17:10