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

﹥>﹥吖頭↗ 提交于 2019-12-25 02:23:26

问题


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.



来源:https://stackoverflow.com/questions/5047212/how-to-use-url-content-asdf-inside-automapper-projection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!