How to use Url.Content ("~ / asdf") inside an autoperson projection

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?

0
source share
1 answer

Mapper.CreateMap<TSource, TDest>()

This should be done only once for the application domain, excellent in the Application_Start method in Global.asax . What you are doing here is that you redefine your matching rules every time the controller is initialized, which is wrong. A great place to do this is to use a custom converter .

0
source

Source: https://habr.com/ru/post/890996/


All Articles