You cannot return an instance of Type
. In order for this to work you'd have to create an instance of Type
which you cannot, at least the version that is being used. Type
is abstract and the runtime creates a derived instance for types at runtime.
Even if you could do that it wouldn't make sense as the bulk of a Type
is just metadata associated with the type that is running on the server. None of this is useful on the client side as all the client gets is the data and it can define its own structure (pulling in only what it wants). The method/constructor/etc members in the metadata and none of that would make it back to the client anyway.
It is important to remember that the big benefit of an API is separation of client/server behavior. The server has all the implementation details and the client just gets the raw data. Any functionality should be handled on the server side otherwise you are spreading functionality across the client and server which defeats the purpose of using APIs.
I'm not really sure why you would ever want to return a type from an API as types are just collections of data and functionality. It almost sounds like you might be using an API when you should really just be using a class library. But assuming you need to do this then you should normalize the Type
to just the data the client needs. For example maybe you need the unique name so return the fully qualified type name. If you want to know what properties are available then expose the property metadata that defines the property name, type and whether it is read only or not. Same thing for methods.
public class TypeInformation
{
public string Name { get; set; }
public IEnumerable<PropertyInformation> Properties { get; set; }
}
public class PropertyInformation
{
public string Name { get; set; }
public string TypeName { get; set; }
public bool IsReadOnly { get; set; }
}
But ultimately none of this is going to be directly usable on the client side. It isn't like they will be able to create a Type
to represent any of that. Your best bet would be to just move the types into a class library and share it on both sides. In that case you just need to expose the actual type instance in the API.
//Sitting in a class library shared by client and server
public class SharedData
{
//Some random data
public string Id { get; set; }
public string Name { get; set; }
}
//API
ActionResult<SharedData> GetData ( int id )
{
SharedData data = ...;
return data;
}
//Client
var data = httpClient.GetJsonAsync<SharedData>(10);