Use "true" or "1" for boolean querystring params
Does anyone use "true" or "false" when setting a query string param for a bool? or do m开发者_运维技巧ost people use "1" or "0". I would be curious to know the consensus out there.
I do prefer "1/0", because it doesn't fall under localization requirements.
bool isTrue = Request.QueryString["value"] == "1";
It may be worth mentioning that when using ASP.NET Core and binding via [FromQuery] you are forced to use boolean values as arguments.
[HttpGet("/api/foo")]
public Task<NoContentResult> FooAction([FromQuery(Name = "bar")] bool isBar) { /*...*/ }
This will work:
GET /api/foo?bar=true
Passing an integer will result in an invalid ModelState
returned by ASP.NET Core's ModelBinder
GET /api/foo?bar=1
You don't have to use either. A query string parameter does not have to have a value. You could just have a uri like this: http://someserver.com/somepage.aspx?SortById=&day=Monday
and then in your code:
if(Request.QueryString.AllKeys.Contains("SortById")) ...
Most sites use true/false on their query strings, so you won't have to switch from 0/1 back to boolean in your code behind (if statement or something). Number is used more for IDs.
It doesn't really matter, to be honest. I've never used a bool in a query string, but I'd probably opt for the '1'.
as long as you validate your input it should be less important. both could be parsed into a boolean value.
keep in mind that the querystring parameter could easily changed from somebody else in his browser.
"true" or "false" is more readable. 1 or 0 saves character in your URL. I prefer 0 or 1. For converting I use Extension Methods:
public static bool GetBoolVal(this HttpRequest r, string name)
{
return r[name] == "1";
}
bool yesnot = Page.Request.GetBoolVal("yesno");
(pseudo code, not tested)
精彩评论