Check for missing (nonexistent / tampered) query string and redirect to a 400 BAD REQUEST page (WebMatrix / Razor syntax)

StackOverflow https://stackoverflow.com/questions/12627212

Domanda

I can test query strings parameters:

Request.QueryString["value"].IsEmpty()
Request.QueryString["value"].Isint()
Etc.

But how can I avoid that there is no query string at all ? In other words, I want to prevent users to access the root of each folder or subfolder.

    http://localhost:16838/auth/provider.cshtml

instead of:

    http://localhost:16838/auth/provider.cshtml?providerId=7

If I remove the query string (up to the page extension), I get a cannot perform runtime binding on a null referenceerror since the next part of the code is still executed.

Instead, I would like the user be redirect to a 400 BAD REQUEST:

The request could not be understood by the server due to malformed syntax.
The client SHOULD NOT repeat the request without modifications
È stato utile?

Soluzione

Users can't "access the root of the folder" by omitting a querystring value. All that will happen if they request http://localhost:16838/auth/provider.cshtml instead of http://localhost:16838/auth/provider.cshtml?providerId=7 is that any code that relies on Request["providerId"] having a value will likely blow up.

If you want to test if a query string value exists, you only need to use IsEmpty():

if(Request["providerId"].IsEmpty()){
    //the value is missing. Redirect ot a safe page or provide a default value
} else {
    //run your code
}

Altri suggerimenti

if you want to make sure there is no query sting value at all you could check Request.ServerVariables["QUERY_STRING"]

http://msdn.microsoft.com/en-us/library/system.web.httprequest.servervariables.aspx

But, most likely you want to be checking individual values and you should be able to do this:

if(Request.QueryString["key"] == null || Request.QueryString["key"].IsEmpty()) 
{
  // redirect
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top