Wednesday, April 6, 2011

Explanation on how this code using web namespace

Hi,

HttpContext context = ((HttpApplication)sender).Context;

In the above example, why do we cast sender to a HTTPApplication and not HTTPContext?

Also, what is the purpose of the brackets? I know they are for casting, but if you get rid of HTTPApplication and the surrounding brackets, that leaves:

(sender).Context;

Why not sender.Context? Or generically, why the use of brackets anyway? I vaguely remember it is a way of casting but can't remember specifics.

Secondly:

 string url = context.Request["url"];
 int cacheDuration = Convert.ToInt32(context.Request["cache"] ?? "0");
 string contentType = context.Request["type"];

EDIT: I realised that you can write:

collection["key"] = "value";

This is for a key-based collection and you store value where there is a key called "key". So am I right in thinking you get the url where the key is "url"?

I know this is using HTTPContext, but in the indexer, what is "url" meant to mean? It is just a string saying url, not even a real url. Likewise for "cache" and "type". If one writes "type", as in the last line of code, does that get back the type (HTTP/HTTPS) used?

Thanks

From stackoverflow
  • It needs to cast sender to HttpApplication because (presumably) that's the actual type - it then gets an HttpContext via the HttpApplication.Context property.

    Given that, you do need the cast, therefore the bracketing is reasonable.

    For the second part: "url", "cache" and "type" are just the names of request parameters (which are documented to come from the cookies, form submission, server variables or URL query parameters). So the original URL might be:

    http://server.com/Foo.aspx?url=someurl&cache=10&type=text/plain

    ... or the values could come from cookies etc. I would hope that given that information, it would be clear where they'd really come from in this case :)

    dotnetdev : Apologies for clarity. I couldn't get the code to be presented in its code view. Anyway, I won't edit at the same time such to prevent data corruption! :)
    dotnetdev : That link covers everything perfectly. Thanks!

0 comments:

Post a Comment