C# 将URL数据与ServiceStack中的HTTP POST请求正文合并
我希望能够将这样的数据发布到REST API:C# 将URL数据与ServiceStack中的HTTP POST请求正文合并,c#,
servicestack,C#,
servicestack,我希望能够将这样的数据发布到REST API: POST /foo/b HTTP/1.1 Accept: application/json Content-Type: application/json { "Qux": 42, "Corge": "c" } foo(即b)之后的URL段也包含我需要在服务器端变量中捕获的数据。我尝试在ServiceStack中实现此功能(请参见下面的代码),但响应主体为null 以下是第一个请求类型: [Route("/foo/{Bar}", "POST")]
POST /foo/b HTTP/1.1
Accept: application/json
Content-Type: application/json
{ "Qux": 42, "Corge": "c" }
foo
(即b
)之后的URL段也包含我需要在服务器端变量中捕获的数据。我尝试在ServiceStack中实现此功能(请参见下面的代码),但响应主体为null
以下是第一个请求类型:
[Route("/foo/{Bar}", "POST")]
public class PostFooRequest : IReturn<PostFooResponse>
{
public string Bar { get; set; }
[ApiMember(ParameterType = "body")]
public Foo Body { get; set; }
}
此外,响应如下所示:
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 };
}
}
最后,服务本身的定义如下:
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 };
}
}
请注意,此方法只是在响应中回显请求的值
当我执行上述请求时,我只返回Bar
值:
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
{"bar":"b"}
在Post
方法中设置断点会显示request.Body
为null
如何编写代码以使API具有所需的契约
FWIW,我知道,但答案只能解释问题所在;不是如何解决它。如果要将当前请求转换为以下数据,序列化程序应该能够填充属性:
[Route("/foo/{Bar}", "POST")]
public class PostFooRequest : IReturn<PostFooResponse>
{
public string Bar { get; set; }
public int Qux { get; set; }
public string Corge { get; set; }
}
检索FormData
的另一种方法是在Servicestack服务中使用以下属性
Request.FormData
。确保您没有调用DTO,而是大写的请求
。@Pilatus answer中的请求DTO显示与您的HTTP请求匹配的请求DTO。注意:当使用像JSON这样的数据格式时,整个请求体总是用来反序列化到请求DTO中,可以进一步由/path/info和querystring填充。另外,[ApiMember]
只是记录API的元数据属性,它们对序列化没有任何影响。