c# - 将 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.Body
是null
.
如何编写代码以使 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 而是调用 capital Request
。
推荐阅读
- ios - 仅当 chrome 调试窗口关闭时,更改才会反映在模拟器中
- powershell - 以正确的顺序对文件进行排序
- c - 在 C 中实现 strcat() 函数
- java - 尽管使用 jna.debug_load=true jna 库似乎并没有打印出其 dll 搜索的步骤。有什么问题?
- powershell - 带有 ESCXLI 的 powerCLI 运行带有用于 Windows 通知的脚本的命令
- jira - 如何在 R4j 中编写嵌套的 if/else 语句(对于 Jira 导出的单词)
- java - Kotlin 弄乱了 java 函数?
- amazon-web-services - AWS IAM 政策对托管实例应用限制——无效的 ARN?
- java - Mockito:Void 类型不抛出异常
- java - 如何获得“AviatorEvaluator”数组对象?