It shows the same content because it resolves the same. As I said if pageid is not passed CurrentPage will default to your first page which is in this case pageid 0. If it was not correctly resolving this you would not see the same content.
My advice is don't put any C# code directly in layout.master. Instead create a user control with your logic an add the user control to layout.master.
In your user control you can get page id like this:
int pageId = WebUtils.ParseIntFromQueryString("pageid", 0);
pass 0 in for the default if its not in the query string since that is your default page.
Still ,it should also work correctly from your user control using:
PageSettings currentPage = CacheHelper.GetCurrentPage();
then using currentPage.PageId.
If the code you have in layout.master is not executing under some circumstances I think there is something else going on to affect it. Try the user control approach.
Hope it helps,