1

在我有这段代码返回一个只有一个 id 属性的任意 json 对象之前。既然不支持 HttpResponseMessage 并且它现在使用 Newtonsofts JSON.NET,如何将其转换为新的 RC 版本的 WebApi?

public HttpResponseMessage<JsonValue> Post(MyModel model)
{
            var id = _theService.AddEntity(model);
            dynamic okResponse = new JsonObject();
            okResponse["id"] = id;
            return new CreateResponse<JsonValue>(okResponse);
}

和...

public class CreateResponse<T> : ResponseBase<T>
    {
        public CreateResponse()
            : base(HttpStatusCode.Created)
        {
        }

        public CreateResponse(T resource)
            : base(resource, HttpStatusCode.Created)
        {
        }
    }

 public abstract class ResponseBase<T> : HttpResponseMessage<T>
    {
        protected ResponseBase(HttpStatusCode httpStatusCode)
            : base(httpStatusCode)
        {
        }

        protected ResponseBase(T resource, HttpStatusCode httpStatusCode)
            : base(resource, httpStatusCode)
        {


            if (resource is IApiResource)
            {
                var apiResource = resource as IApiResource;
                var resourceLocation = new ResourceLocation();
                apiResource.SetLocation(resourceLocation);
                Headers.Location = resourceLocation.Location;
            }
        }
    }
4

3 回答 3

2

CreateResponse 扩展方法不接受动态变量。

请更换

dynamic okResponse = new JsonObject();

类似于

var okResponse = new JsonObject();

另请参阅此链接: https ://aspnetwebstack.codeplex.com/discussions/359242

于 2012-06-16T10:52:38.730 回答
2

Request.CreateResponse(statuscode, content)在控制器内部使用

于 2012-06-15T14:22:54.413 回答
0

也许我在你的问题中遗漏了一些东西,但你可以这样做:

public dynamic Post(MyModel model)
{
            var id = _theService.AddEntity(model);


            return new { id = id };
}

编辑:假设您的客户将 Content-type 设置为 application/json

于 2012-06-16T01:11:50.383 回答