質問

Edit: Found the answer (in comments).

Currently, I am using System.Web.Http.ApiController to access some object in the memory of a server. These objects can have any type.

I use the following api controller to receive them: (example code. Not the full source code)

public class DataController : ApiController
{
    Dictionary<String, Object> _dataDict;

    public object Get(string dataPath)
    {
        Object result = _dataDict[dataPath];
        return result;
    }
}

This works fine to receive all my objects in JSON via the web api. The problem is sending new objects using POST:

public class DataController : ApiController
{
    Dictionary<String, Object> _dataDict;

    public object Get(string dataPath)
    {
        Object result = _dataDict[dataPath];
        return result;
    }
    public void Post(string dataPath, Object obj)
    {
        _dataDict[dataPath] = obj;
    }
}

The Object will be a dynamic object instead of the real deserialized object. Implementing a concrete method such as:

public object Post(string dataPath, MyClass instance)
{
    _dataDict[dataPath] = instance;
}

works fine. Sadly, I don't know all used types at runtime but I know which type it is by analzing dataPath and can get the Type instance at runtime. How can I tell the formatter or the ApiController (I don't know who actually creates the instance) to create to correct instance using the correct Type ?

I am using System.Net.Http.Formatting.JsonMediaTypeFormatter.

Thanks in advance.

devluz

役に立ちましたか?

解決

Well ok it is actually a JObject and not a dynamic object. The embarrassing answer is:

public void Post(string dataPath, JObject obj)
{
    Type myClass = figureOutMyTypeByParsingThePath(dataPath);
    _dataDict[dataPath] = obj.ToObject(myClass);
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top