This repository was archived by the owner on Dec 14, 2018. It is now read-only.
This repository was archived by the owner on Dec 14, 2018. It is now read-only.
UrlHelperFactory.GetUrlHelper may throw an exception #5170
Closed
Description
While trying to mock a controller I came across a KeyNotFoundException
in the UrlHelperFactory
's GetUrlHelper
method.
It seems the following code relies on the typeof(IUrlHelper)
key already populated in the Items
collection:
// Perf: Create only one UrlHelper per context
var urlHelper = httpContext.Items[typeof(IUrlHelper)] as IUrlHelper;
if (urlHelper == null)
{
urlHelper = new UrlHelper(context);
httpContext.Items[typeof(IUrlHelper)] = urlHelper;
}
If the key is missing, this line throws an exception, instead of returning null
. I believe that the following code should be used instead:
// Perf: Create only one UrlHelper per context
object urlHelper;
if (!httpContext.Items.TryGetvalue(typeof(IUrlHelper), out urlHelper)
|| !(urlHelper is IUrlHelper))
{
urlHelper = new UrlHelper(context);
httpContext.Items[typeof(IUrlHelper)] = urlHelper;
}
return (IUrlHelper)urlHelper;