首页 > 解决方案 > 将 URL 数据与 ServiceStack 中的 HTTP POST 请求正文结合起来

问题描述

我希望能够将这样的数据发布到 REST API:

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

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

foo(ie )之后的 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定义如下:

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,我知道这个问题,但答案只解释了问题所在;不是如何解决它。

标签: c#servicestack

解决方案


如果您将当前请求转换为以下 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 而是调用 capital Request


推荐阅读