Skip to content
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
@vdachev

Description

@vdachev

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;

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions