Monday, February 27, 2012

MakeGenericType to the rescue

I have a need to return a HttpResponseMessage<> in an ActionFilterAttribute with ActionDescriptor.ReturnType. All my response object belong to a single base class. Anyway, here is how I did it.

private static void SetInvalidRequestResponse(HttpActionContext context)
{
  var returnType = context.ActionDescriptor.ReturnType;
    
  var response = Activator.CreateInstance(returnType) as BaseResponse;
  var request = context.ActionArguments.First().Value as BaseRequest;

  response.ResponseCode = "Invalid request";

  if (request != null)
  {
    response.SourceId = request.SourceId;
    response.Uuid = request.Uuid;
  }

  var genericType = typeof (HttpResponseMessage<>)
    .MakeGenericType(new[] {returnType});

  context.Response = Activator
    .CreateInstance(genericType, response, HttpStatusCode.Forbidden)
      as HttpResponseMessage;
}

No comments: