在匿名类型中指定一个 属性 的名称?

Specify the name of a property in an anonymous type?

在网络 api 中,我正在 returning 匿名类型,如下所示:

return Request.CreateResponse(HttpStatusCode.OK, new
{
    SomeNameHere = new {Message = "my message"}
});

我正在尝试编写这样的扩展方法:

public static class RequestExtensions
    {
        public static HttpResponseMessage CreateMyResponse(
            this HttpRequestMessage httpRequestMessage,
            HttpStatusCode statusCode, 
            string wrapper, 
            string message)
        {
            return httpRequestMessage.CreateResponse(statusCode, new
            {
                wrapper = new
                {
                    Message = message
                }
            });
        }
    }

它会这样称呼:

return Request.CreateMyResponse(HttpStatusCode.OK, "SomeCommand", "some message");

但是,当我 运行 这并在邮递员中测试端点时,这就是我得到的结果:

{ "wrapper": { "Message": "some message" } }

我明白为什么这行不通,我只是想找到一个替代解决方案来代替 return:

{ "SomeCommand": { "Message": "some message" } }

我知道我可以制作这个对象,然后 return 那样做,但是我不想像这样一次性创建一大堆新对象。任何帮助深表感谢。谢谢。

看起来使用 ExpandoObject 会起作用!

public static HttpResponseMessage CreateWrappedResponse(
    this HttpRequestMessage httpRequestMessage,
    HttpStatusCode statusCode,
    string rootTagName,
    string message)
{
    dynamic messageObject = new ExpandoObject();
    dynamic wrapperObject = new ExpandoObject();

    var messageDictionary = (IDictionary<string, object>)messageObject;
    messageDictionary.Add("Message", message);
    var wrapperDictionary = (IDictionary<string, object>)wrapperObject;
    wrapperDictionary.Add(rootTagName, messageDictionary);

    return httpRequestMessage.CreateResponse(statusCode, wrapperDictionary);
}

我可以这样调用扩展方法:

return Request.CreateWrappedResponse(HttpStatusCode.OK, "SomeCommand", "some message");

这将 return 我的 json 在邮递员中,就像我想要的那样:

{ "SomeCommand": { "Message": "some message" } }