如何使用Url.Content(QUOT;〜/ ASDF&QUOT)automapper投影内 [英] How to use Url.Content("~/asdf") inside automapper projection
问题描述
我试图使用UrlHelper的内容方法的automapper投影里面,但第一次请求之后失败。
I am trying to use the UrlHelper's Content method inside an automapper projection, but it fails after the first request.
我的地图创建code如下所示:
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));
}
第一个请求工作正常,但后续请求抛出以下堆栈跟踪一个NullReferenceException:
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)
有趣的是,如果我映射之前缓存Url.Content()的一部分,东西做工精细:
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这个code被简化,但对于我的使用情况下,它作为一个JSON响应的一部分,所以我不能Url.Content()部分移动到一个视图。
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.
这是一个automapper问题,一个MVC问题,或者我在做正确更容易一些?是否有映射code?
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?
推荐答案
Mapper.CreateMap&LT; TSource,TDest&GT;()
这应该做的每个应用程序域只有一次,完全在的Application_Start
方法的Global.asax
。你在这里做什么是你重新定义你的映射规则每次控制器初始化这是不正确的。一个伟大的地方要做到这一点是使用自定义解析
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.
这篇关于如何使用Url.Content(QUOT;〜/ ASDF&QUOT)automapper投影内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!