Search code examples
c#nullhttpcontext

Null in context.Request


How to allow null in Context.Request:

context.Response.Write(retrieveList(context.Request["SalCode"].ToString(null), context.Request["groupKeyword"].ToString(), context.Request["text"].ToString()));

Solution

  • Firstly, Request["..."] already returns a string, so there is no need to call ToString() on it and thus no need to worry, at this stage, if it returns null (i.e. if the key is not present in the request).

    Thus you can call e.g.

    retrieveList(
        context.Request["SalCode"],
        context.Request["groupKeyword"],
        context.Request["text"]);
    

    without worrying if any of the three are null.

    You can then alter retrieveList to respond correctly if any of the inputs is null. For example, you could return null:

    private string /*or whatever*/ retrieveList(
        string salCode, string groupKeyword, string text)
    {
        if (String.IsNullOrEmpty(salCode) ||
            String.IsNullOrEmpty(groupKeyword) ||
            String.IsNullOrEmpty(text))
        {
            return null;
        }
        ...
    }
    

    Then, note that Response.Write doesn't care if you give it a null, it just writes nothing, so you can keep the call to Write as above.

    Alternatively, you could for example check the return value and write a message if it is null:

    var list = retrieveList(
        context.Request["SalCode"],
        context.Request["groupKeyword"],
        context.Request["text"]));
    if (!String.IsNullOrEmpty(list))
    {
        context.Response.Write(list);
    }
    else
    {
        context.Response.Write("Missing request parameter.");
    }