Automapper和Url.Content

时间:2014-08-14 16:08:34

标签: c# asp.net-mvc automapper

我有一个MVC5控制器,可以将DTO转换为ViewModel。

model.Items = items.Select(i => new MovieSearchItem
{
    Id = i.Id,
    Image = (string.IsNullOrWhiteSpace(i.Image) ? @Url.Content("~/Content/noMovieImage.png") : i.Image),
    Title = i.Title
}).ToList();

我尝试使用Automapper做同样的事情。

Mapper.CreateMap<MovieDTO, MovieSearchItem>()
    .ForMember(m => m.Image,
        opt => opt.MapFrom(src => GetConversionForMovieSearchItem()(src)));

所谓的函数是:

public Func<MovieDTO, string> GetConversionForMovieSearchItem()
{
    return new Func<MovieDTO, string>(src =>
    {
        var image = string.IsNullOrWhiteSpace(src.Image) ? @Url.Content("~/Content/noMovieImage.png")
                            : src.Image;
        return image;
    });
}

执行映射时,会抛出异常:

  

类型&#39; System.ArgumentException&#39;的例外情况发生在mscorlib.dll中但未在用户代码中处理

     

其他信息:价值不在预期范围内。

堆栈跟踪是:

at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
   at System.Runtime.InteropServices.Marshal.ThrowExceptionForHR(Int32 errorCode)
   at System.Web.Hosting.IIS7WorkerRequest.GetServerVariableInternal(String name)
   at System.Web.Hosting.IIS7WorkerRequest.GetServerVariable(String name)
   at System.Web.WebPages.UrlRewriterHelper.WasThisRequestRewritten(HttpContextBase httpContext)
   at System.Web.WebPages.UrlRewriterHelper.WasRequestRewritten(HttpContextBase httpContext)
   at System.Web.WebPages.UrlUtil.GenerateClientUrlInternal(HttpContextBase httpContext, String contentPath)
   at System.Web.WebPages.UrlUtil.GenerateClientUrlInternal(HttpContextBase httpContext, String contentPath)
   at System.Web.WebPages.UrlUtil.GenerateClientUrl(HttpContextBase httpContext, String contentPath)
   at System.Web.Mvc.UrlHelper.GenerateContentUrl(String contentPath, HttpContextBase httpContext)
   at Pinicules.Presentation.Controllers.MoviesController.<GetConversionForMovieSearchItem>b__0(MovieDTO src) in c:\Repositories\GitHub\Pinicules\Pinicules.Presentation\Controllers\MoviesController.cs:line 23
   at lambda_method(Closure , MovieDTO )
   at AutoMapper.DelegateBasedResolver`2.Resolve(ResolutionResult source)
   at AutoMapper.NullReferenceExceptionSwallowingResolver.Resolve(ResolutionResult source)
   at AutoMapper.PropertyMap.<ResolveValue>b__6(ResolutionResult current, IValueResolver resolver)
   at System.Linq.Enumerable.Aggregate[TSource,TAccumulate](IEnumerable`1 source, TAccumulate seed, Func`3 func)
   at AutoMapper.PropertyMap.ResolveValue(ResolutionContext context)
   at AutoMapper.Mappers.TypeMapObjectMapperRegistry.PropertyMapMappingStrategy.MapPropertyValue(ResolutionContext context, IMappingEngineRunner mapper, Object mappedObject, PropertyMap propertyMap)

为什么会发生这种错误?为什么我能够使用Automapper?

谢谢!

0 个答案:

没有答案