I am trying to use the UrlHelper content method inside the automapper projection, but it does not work after the first request.
My map creation code is as follows:
protected override void Initialize(RequestContext requestContext) { base.Initialize(requestContext); Mapper.CreateMap<MyObject, MyMappedObject>() .ForMember(dest => dest.Url, opt => opt.MapFrom(src => Url.Content("~/something/") + src.Id)); }
The first request works fine, but subsequent requests raise a NullReferenceException with the following stack trace:
at System.Web.HttpServerVarsCollection.Get(String name) at System.Web.Mvc.UrlRewriterHelper.WasThisRequestRewritten(HttpContextBase httpContext) at System.Web.Mvc.UrlRewriterHelper.WasRequestRewritten(HttpContextBase httpContext) at System.Web.Mvc.PathHelpers.GenerateClientUrlInternal(HttpContextBase httpContext, String contentPath) at System.Web.Mvc.PathHelpers.GenerateClientUrlInternal(HttpContextBase httpContext, String contentPath) at System.Web.Mvc.PathHelpers.GenerateClientUrl(HttpContextBase httpContext, String contentPath) at System.Web.Mvc.UrlHelper.GenerateContentUrl(String contentPath, HttpContextBase httpContext) at System.Web.Mvc.UrlHelper.Content(String contentPath)
The interesting part is that if I cache the Url.Content () part before displaying, everything works fine:
protected override void Initialize(RequestContext requestContext) { base.Initialize(requestContext); var url = Url.Content("~/something/"); Mapper.CreateMap<MyObject, MyMappedObject>() .ForMember(dest => dest.Url, opt => opt.MapFrom(src => url + src.Id)); }
This code is simplified, but for my use it is used as part of a json response, so I cannot move part of Url.Content () to the view.
Is this a problem with auto personnel, an MVC problem, or rather something I'm doing wrong? Is there a cleaner solution other than "caching" part of the url in a variable before the display code?