0

I decided to create a function to encapsulate many lines of codes into 1 line of code. So hence this example script. What I could not get to work is get the class's Type and pass it on to ObjectContent's parameter for it to work.

Take a look at xmlObjectType variable in ObjectContent<xmlObjectType>(....) and the System.Type assignment to xmlObjectType using GetType() on the passed-in paramater object. What do you guys do to get the actual object type for this to work with ObjectContent?

public class XmlError
{
    public string Message { get; set; }
}
public class XmlBuilderTools 
{
   public HttpResponseMessage ErrorResponse(object parmXmlErrorLayout)
   {
       HttpResponseMessage httpResponseMsg = new HttpResponseMessage();
       Type xmlObjectType = parmXmlErrorLayout.GetType();

       httpResponseMsg.StatusCode = HttpStatusCode.BadRequest;
       httpResponseMsg.Content = new ObjectContent<xmlObjectType>(parmXmlErrorLayout, new XmlMediaTypeFormatter());
   }
}

//Acutual scripts...
XmlBuilderTools xmlBuilderTools = new XmlBuilderTools();
XmlError xmlError = new XmlError();

xmlError.Message = "Foo";

return xmlBuilderTools.ErrorResponse(xmlError);

Edited - Found a workaround to this problem. You do not have to invoke it, instead do use other object overloading that works. Me Duh!

 httpResponseMsg.Content = new ObjectContent(parmXmlErrorLayout.GetType(), parmXmlErrorLayout, new CustomXmlFormatter());
fletchsod
  • 3,181
  • 6
  • 31
  • 58
  • Unlike forum sites, we don't use "Thanks", or "Any help appreciated", or signatures on [so]. See "[Should 'Hi', 'thanks,' taglines, and salutations be removed from posts?](http://meta.stackexchange.com/questions/2950/should-hi-thanks-taglines-and-salutations-be-removed-from-posts). – John Saunders Dec 10 '14 at 19:08

1 Answers1

0

You simply can't do that. You have to use reflection instead.

MethodInfo method = yourInstance.GetType().GetMethod("ObjectContent").MakeGenericMethod(new Type[] { xmlObjectType });
method.Invoke(this, new object[] { parmXmlErrorLayout, new XmlMediaTypeFormatter() });

Otherwise pass the type as a parameter to method too.

dario
  • 4,811
  • 12
  • 26
  • 31