在 ServiceStack 中将 URL 数据与 HTTP POST 请求正文合并

Combine URL data with HTTP POST request body in ServiceStack

我希望能够 POST 像这样的数据到 REST API:

POST /foo/b HTTP/1.1
Accept: application/json
Content-Type: application/json

{ "Qux": 42, "Corge": "c" }

foo 之后的 URL 段(即 b)也包含我需要在服务器端变量中捕获的数据。我试图在 ServiceStack 中实现此功能(请参阅下面的代码),但响应主体是 null.

首先是请求类型:

[Route("/foo/{Bar}", "POST")]
public class PostFooRequest : IReturn<PostFooResponse>
{
    public string Bar { get; set; }

    [ApiMember(ParameterType = "body")]
    public Foo Body { get; set; }
}

如您所见,Bar 是一个 URL 变量。 Foo class 定义如下:

public class Foo
{
    public int Qux { get; set; }
    public string Corge { get; set; }
}

此外,响应如下所示:

public class PostFooResponse
{
    public string Bar { get; set; }
    public Foo Foo { get; set; }
}

最后,服务本身是这样定义的:

public class ReproService : Service
{
    public object Post(PostFooRequest request)
    {
        return new PostFooResponse { Bar = request.Bar, Foo = request.Body };
    }
}

请注意,此方法只是在响应中回显 request 的值。

当我执行上述请求时,我只得到Bar值:

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8

{"bar":"b"}

Post方法中设置断点显示request.Bodynull

如何编写代码才能使 API 拥有所需的合同?

FWIW,我知道 ,但答案只说明了问题所在;不是怎么解决的。

如果您将当前请求转换为以下 DTO,序列化程序应该能够填充属性:

[Route("/foo/{Bar}", "POST")]
public class PostFooRequest : IReturn<PostFooResponse>
{
    public string Bar { get; set; }

    public int Qux { get; set; }
    public string Corge { get; set; }
}

序列化程序无法知道如何反序列化您发送的对象。

查看您的 DTO 和请求,我希望有不同的请求。

POST /foo/b HTTP/1.1
Accept: application/json
Content-Type: application/json

{
    "Foo": {  "Qux": 42, "Corge": "c" }
}

检索 FormData 的其他方法是在您的 Servicestack 服务中使用以下 属性 Request.FormData。确保你不是在调用 DTO,而是调用大写 Request.