i'm trying reconcile few opinions i've found out in wild. 1 source says in c# request.urlreferrer throw system.uriformatexception if http header malformed. other says request.urlreferrer doesn't throw exception in case, returns null.
that said, i'm developing webapp capture referral url future reference. i'm checking null "not set instance of object" error not burst forth when converting string, etc., , tests out fine. wondering whether should include error handling potential system.uriformatexceptions.
has run this? thank you!
edit: given nightowl888's answer below, appear exceptions can occur. how often, i'm not sure, i'd rather protect against risk exceptions on public site.
i grabbing referralurl logging, won't used in downstream application context. it's getting granngiven that, i'm guessing following code should cover me:
uri referrer = null; try { referrer = request.urlreferrer; } catch (uriformatexception) { referrer = null; } catch (exception) { referrer = null; } var referralurl = (referrer != null) ? referrer.tostring() : "none found";
edit: changed exceptions , added general catch
checking source of system.web.httpcontext.current.request.urlreferrer
shows following.
public uri urlreferrer { { if ((this._referrer == null) && (this._wr != null)) { string knownrequestheader = this._wr.getknownrequestheader(0x24); if (!string.isnullorempty(knownrequestheader)) { try { if (knownrequestheader.indexof("://", stringcomparison.ordinal) >= 0) { this._referrer = new uri(knownrequestheader); } else { this._referrer = new uri(this.url, knownrequestheader); } } catch (httpexception) { this._referrer = null; } } } return this._referrer; } }
so, indeed possible uriformatexception
can occur if url malformed, since httpexception
type set null
, uriformatexception
not inherit httpexception
.
a better option may use request.headers["referer"]
, return raw string pointed out here. note header can contain value (including values not urls).
imo, referer
header should used logging purposes because not reliable enough use implementing kind of application functionality (unless there kind of backup functionality in case missing or malformed). browser can (and does) neglect send in cases.