How to use Url.Content(“~/asdf”) inside automapper

2019-09-17 16:13发布

问题:

I am trying to use the UrlHelper's Content method inside an automapper projection, but it fails after the first request.

My map creation code looks like the following:

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 throw 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 if I cache the Url.Content() part before the mapping, things work 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));
}

btw this code is simplified, but for my use case it is used as part of a json response, so I cannot move the Url.Content() part to a view.

Is this an automapper issue, an MVC issue, or more likely something I'm doing incorrectly? Is there a cleaner solution other than just "caching" the url part in a variable before the mapping code?

回答1:

Mapper.CreateMap<TSource, TDest>()

This should be done only once per App Domain, perfectly in the Application_Start method in Global.asax. What you do here is that you redefine your mapping rules everytime a controller is initialized which is not correct. A great place to do this is to use a custom resolver.