简体   繁体   中英

How do I handle a request when the request parameter does not exist?

I'm redirecting from one page to another by sending an id via url and then getting it through the "Request". The problem I have is that there are two ways to get to the page.

  1. Going through the link that will send you onwards with an id in the url. (this works)
  2. By directly going to the page thus not bringing any id with you. (this does not and thows the error)

Exception Details: System.InvalidOperationException: Nullable object must have a value.

How the links will look when you are redirected for scenario 1 and when you go directly in scenario 2.

1. http://localhost/red/time/time.aspx?id=154

2. http://localhost/red/time/

    if (!IsPostBack)
    {

        //Bladdra(4, 0);
        txtTidrapportnr.Text = Request["id"];

        if (Request != null)
        {
            Hamta(General.ToInt(txtTidrapportnr.Text).Value);
            Visa();
            btnNy.Focus();
        }
        else
        {
            Bladdra(4, 0);
            Visa();
            btnNy.Focus();
        }


    }

My question is how do I get the page to work both in scenario 1 and 2. It seems like

if (Request != null)

is not correct.

You are doing a wrong thing is that befor checking the null value you are trying to assign it with textbox value the proper method to doing things is as follow:

if (!IsPostBack)
    {

        //Bladdra(4, 0);
        //txtTidrapportnr.Text = Request["id"];

        if (Request["id"] != null)
        {
            txtTidrapportnr.Text =Convert.ToString(Request["id"]);

            Hamta(General.ToInt(txtTidrapportnr.Text).Value);
            Visa();
            btnNy.Focus();
        }
        else
        {
            Bladdra(4, 0);
            Visa();
            btnNy.Focus();
        }


    }

If your page should only work when the id request parameter then you will have to check for its presence yourself as others have suggested - you cannot stop a page from being accessed automatically as there is nothing stopping you from hitting the URL manually from a browser.

If the parameter is not present you should then handle it gracefully. A typical method I use is to redirect to a known safe page (eg homepage) if the URL does not contain everything I need, but I suppose you could also display a warning message on the page as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM