2

I'm trying to introduce automapper in such a way that for WebAPI all DTOs are transparent, so basically I want to map objects in runtime and convert them to Domain objects before they reach controller method.

I have automapper filter attribute

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
    public class AutoMapAttribute : ActionFilterAttribute
{
    private readonly Type _sourceType;
    private readonly Type _destType;

    public AutoMapAttribute(Type sourceType, Type destType)
    {
        _sourceType = sourceType;
        _destType = destType;
    }

    #region Overrides of ActionFilterAttribute

    /// <summary>Occurs before the action method is invoked.</summary>
    /// <param name="actionContext">The action context.</param>
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        var mapper = ServiceLocator.Locator.GetInstance<IMapper>();
        var jsonObject = actionContext.ActionArguments.FirstOrDefault(x => x.Value.GetType() == typeof(Newtonsoft.Json.Linq.JObject));
        var dto = JsonConvert.DeserializeObject(jsonObject.Value.ToString(), _sourceType);
        object model = mapper.Map(dto, _sourceType, _destType);

        actionContext.ActionArguments[jsonObject.Key] = model;

        base.OnActionExecuting(actionContext);
    }

    #endregion

    #region Overrides of ActionFilterAttribute

    /// <summary>Occurs after the action method is invoked.</summary>
    /// <param name="actionExecutedContext">The action executed context.</param>
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        base.OnActionExecuted(actionExecutedContext);
    }

    #endregion

    public Type SourceType
    {
        get { return _sourceType; }
    }

    public Type DestType
    {
        get { return _destType; }
    }
}

and controller method:

    [HttpPost]
    [Route("")]
    [AutoMap(typeof(Public.Dto.Product), typeof(Domain.Model.Product))]
    public IHttpActionResult Post(object product)
    {
        _productBusinessLogic.Create(product);
        return Ok();
    }

and it works quite well as product variable in controlelr method is actually my Domain product. Now I want to change object type to concrete Domain.Product type in controller method definition. Unfortunately WebAPI tries to immediately deserialize object that comes from Request to this object type which breaks the whole idea.

I am able to use OWIN if it helps.

4
  • Are you using OWIN? Jul 26, 2016 at 12:02
  • Please see my updated answer.
    – VsMaX
    Jul 26, 2016 at 13:08
  • don't you want to make the concrete type to be the public DTO type, not the domain model type? Or, if you make the domain model the concrete type, then surely you don't need automapper?? Or have I got it the wrong way round?
    – ADyson
    Jul 26, 2016 at 13:35
  • no, i just want the DTO to be totally transparent to WebAPI, so the mapping to DTO is done by convention
    – VsMaX
    Jul 26, 2016 at 16:27

1 Answer 1

0

The key point is that the handling of action filters takes place after model binding in the Web API request stack.

Using OWIN we could read the original body as the source type and then map it to the target type:

  1. Override the OnActionExecutingAsync method:

    public override async Task OnActionExecutingAsync(HttpActionContext actionContext,
        CancellationToken cancellationToken)
    {
        var argumentKey = actionContext.ActionArguments.FirstOrDefault().Key;
    
        var owinContext = (OwinContext) actionContext.Request.Properties["MS_OwinContext"];
    
        owinContext.Request.Body.Seek(0, SeekOrigin.Begin);
    
        var source = await actionContext.Request.Content.ReadAsAsync(_sourceType, cancellationToken);
    
        actionContext.ActionArguments[argumentKey] = Mapper.Map(source, _sourceType, _destType);
    
        await base.OnActionExecutingAsync(actionContext, cancellationToken);
    }
    
  2. To reread the request's content in the action filter we need to add some handler to the pipeline in the OWIN Startup class:

    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            var config = new HttpConfiguration();
    
            app.Use(async (context, next) =>
            {
                var content = context.Request.Body;
    
                if (content == Stream.Null)
                {
                   await next();
                }
                else
                {
                    using (var stream = new MemoryStream())
                    {
                        await content.CopyToAsync(stream);
    
                        stream.Position = 0;
    
                        context.Request.Body = stream;
    
                        await next();
                    }
    
                    context.Request.Body = content;
                }
            });
    
            app.UseWebApi(config);        
        }
    }
    
3
  • Could you please explain a little bit more why we need to "reread" content in actionfilter? Does it mean that we still try to deserialize into object defined in Controller and then discard this value by using point 2. ? Is there a way not to deserialize to the controller type in the first place?
    – VsMaX
    Jul 27, 2016 at 8:08
  • @VsMax the model binding in the method Post(Domain.Model.Product) will be processed at first and the request context will be read so that the context stream is no more readable afterward. So, yes we deserialize the content twice, first in the controller and then in the filter. I hope there is a clean/right way to achieve the same without multiple deserialization. Well you could getting it work by misusing the AuthorizeAttribute and doing the type mapping in OnAuthorization method and overriding IsAuthorized(HttpActionContext actionContext) => true. But as I said it's not that clean. Jul 27, 2016 at 11:45
  • it works, although I had to adjust some other pieces of code to make it working :) thank you.
    – VsMaX
    Jul 28, 2016 at 7:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.