Fresh coming in from accepted answer at How do I get object type and passed it on to ObjectContent, which was about passing in class
type to newly created function having ObjectContent
object in it to work.
My next step is to convert it to static class/functions. To the best of my ability, I'm getting exception error when assigning type.GetMethod("ObjectContent", ...)
to methodInfo
variable.
The error message is "Object reference not set to an instance of an object".
What seems to be the problem here with type.GetMethod("ObjectContent", ...)
? What's the workaround to this problem?
public class XmlError
{
public string Message { get; set; }
}
public static class XmlBuilderTools
{
public static HttpResponseMessage ErrorResponse(object parmXmlErrorLayout)
{
HttpResponseMessage httpResponseMsg = new HttpResponseMessage();
Type type = parmXmlErrorLayout.GetType(); //typeof(parmXmlErrorLayout);
System.Reflection.MethodInfo methodInfo = type.GetMethod("ObjectContent", (System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.FlattenHierarchy));
returnHttpResponseMessage.Content = (HttpContent)methodInfo.Invoke(null, new object[] { parmXmlErrorLayout, new XmlMediaTypeFormatter() });
httpResponseMsg.StatusCode = HttpStatusCode.BadRequest;
}
}
public class Foo()
{
public HttpResponseMessage FooFoo()
{
//Acutual scripts...
XmlError xmlError = new XmlError();
xmlError.Message = "Foo";
return XmlBuilderTools.ErrorResponse(xmlError);
}
}
Originally this would work in non-static class/object
returnHttpResponseMessage.Content = new ObjectContent<XmlError>(xmlError, new CustomXmlFormatter());