views:

70

answers:

1

This is a follow-up to http://stackoverflow.com/questions/3444000/choosing-a-connection-string-based-on-kind-of-request for which I got no answer and what I thought worked doesn't.

I have a webservice that needs to choose a specific connection string based on the user calling it from a browser or from a client application.

I tried:

HttpContext.Current != null? ConnectionStrings["Website"].ConnectionString : ConnectionStrings["Client"].ConnectionString

but realized that at some point even if I'm using the client application, there is some HttpContext (if someone can explain why it'd be great) but the Browser field under Request is "Unknown". So, then I tried:

if ( HttpContext.Current != null )
{
  if ( HttpContext.Current.Request.Browser != "Unknown" )
  {
     //browser connection string here
  }
  else
     //client app connection string here
}
else
  //client app connection string here

This worked wonders when debugging, but on testing environment it still points to Browser connection string even when calling from the client app, as if at some point the Browser isn't "Unknown" ...

Is there a MUCH easier/simpler way to do this? The way I'm doing it seems really ugly.

I'm quite desperate at the moment as I have no idea why this is happening..

+1  A: 

Rather than detecting and switching on the browser type, consider these two suggestions:

Add Custom Request Headers

In your various callers, define a new custom header in your Http request.

HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Headers.Add("CallerType", "ClientApp"); // "Browser", etc.

Then you know exactly and reliably what type of client is calling. This would be hard to get wrong, and couldn't be spoofed/mistaken.

Include The Caller Type in the QueryString

myService.asmx?BrowserType=1

Add a simple new querystring parameter to your .asmx webmethod. This will work just the same in a controlled environment, but if other users/developers get it wrong, or malform the expected values, you'd have to take other measures to correct/handle.

Both allow you to easily determine the connString on the incoming value. Perhaps the absense of a modifier/header, you could assume a default. Your sample question has 2 basic outcomes, and either suggested solution will be easy to extend (browser, client app, iPhone, whathaveyou).

p.campbell