在web api中,我正在返回匿名类型:
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");
然而,当我运行这个并在postman中测试端点时,这就是我得到的:
{“wrapper”:{ “消息”:“某些消息”}}
我理解为什么这不起作用,我只是想找到一个可以正确返回的替代解决方案:
{“SomeCommand”:{ “消息”:“某些消息”}}
我意识到我可以制作这个对象并以这种方式返回它,但是我不想像这样一次创建一大堆新对象。任何帮助深表感谢。感谢。
答案 0 :(得分:0)
看起来使用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");
这会像我想要的那样以邮递员的形式返回我的json:
{&#34; SomeCommand&#34;:{&#34; Message&#34;:&#34; some message&#34; }}