Passing Session[] and Request[] to Methods in C#
In C#, How do you pass the Session[] and Request[] objects to a method?
I would like to use a method to parse out Session and Request paramaters for a .aspx page to reduce the size of my Page_Load method. I am passing quite a few variables, and need to support both POSTand GET methods. For most calls, not all variables are present, so I have to test every variable multiple ways, and the code gets long...
This is what I am trying to do, but I can't seem to properly identify the Session and Request paramaters (this code will not compile, because the arrays are indexed by number)
static string getParam(
System.Web.SessionState.HttpSessionState[] Session,
System.Web.HttpRequest[]开发者_运维知识库 Request,
string id)
{
string rslt = "";
try
{
rslt = Session[id].ToString();
}
catch
{
try
{
rslt = Request[id].ToString();
}
catch { }
}
return rslt;
}
From Page_Load, I want to call this method as follows to retrieve the "MODE" paramater:
string rslt;
rslt = getParam(Session, Request, "MODE");
Thanks!
You don't need to declare them as array parameters; they aren't arrays they are just a single object. So your functions signature should look something like this:
static string getParam(
System.Web.SessionState.HttpSessionState Session,
System.Web.HttpRequest Request,
string id)
With just that change your code should work, but it could be improved quite a bit, for example the following does the same but without the risk of NullReferenceException
:
private static string GetParameter(
HttpSessionState session,
HttpRequest request,
string id)
{
var value = session[id] ?? request[id];
return value == null ? string.Empty : value.ToString();
}
A couple of points worth noting:
Follow the style guidelines you see in the framework. That means the same casing of function names, parameter names, etc. Also, don't abbreviate words (i.e. use 'parameter' instead of 'param'). It's also a good idea to explicitly declare access modifiers (i.e. if you mean a method to be private, then write
private
).Never, ever, use
try/catch
to catch non-specific exceptions. You could end up attempting to swallow asynchronous exceptions like out-of-memory or thread-abort which is a recipe for disaster. If you don't know why you shouldn't catch non-specific exceptions, then it's even more reason not to until you do know.Never, ever, catch
NullReferenceException
(which I suspect is the exception that is frequently happening here and why thetry/catch
blocks are there). Any time this exception is thrown it is a bug in your code that you need to fix. Unlike most rules of development, there are no exceptions to this rule.
What's wrong with
rslt = Session["MODE"] != null ? Session["Mode"] : Request["Mode"];
rslt = rslt ?? "someDefaultValue";
?
精彩评论