![](/img/trans.png)
[英]How to set default content-type to Json with servicestack serializer
[英]Content-Type must be 'application/json-patch+json' JsonServiceClient ServiceStack
我正在尝试使用JsonServiceClient对服务堆栈api执行补丁,如下所示:
var patchRequest = new JsonPatchRequest
{
new JsonPatchElement
{
op = "replace",
path = "/firstName",
value = "Test"
}
};
_jsonClient.Patch<object>($"/testurl/{id}", patchRequest);
但我收到以下错误:
内容类型必须为'application / json-patch + json'
错误很明显。 有没有一种方法可以在执行对JsonServiceClient的请求之前更改内容类型?
这是ServiceStack API中的请求POCO:
[Api("Partial update .")]
[Route("/testurl/{Id}”, "PATCH")]
public class PartialTest : IReturn<PartialTestRequestResponse>, IJsonPatchDocumentRequest,
IRequiresRequestStream
{
[ApiMember(Name = “Id”, ParameterType = "path", DataType = "string", IsRequired = true)]
public string Id { get; set; }
public Stream RequestStream { get; set; }
}
public class PartialTestRequestResponse : IHasResponseStatus
{
public ResponseStatus ResponseStatus { get; set; }
}
服务实施:
public object Patch(PartialTest request)
{
var dbTestRecord = Repo.GetDbTestRecord(request.Id);
if (dbTestRecord == null) throw HttpError.NotFound("Record not found.");
var patch =
(JsonPatchDocument<TestRecordPoco>)
JsonConvert.DeserializeObject(Request.GetRawBody(), typeof(JsonPatchDocument<TestRecordPoco>));
if (patch == null)
throw new HttpError(HttpStatusCode.BadRequest, "Body is not a valid JSON Patch Document.");
patch.ApplyTo(dbTestRecord);
Repo.UpdateDbTestRecord(dbTestRecord);
return new PartialTestResponse();
}
我正在使用Marvin.JsonPatch V 1.0.0库。
目前尚不清楚异常的来源,因为它不是ServiceStack中的错误。 如果您注册了引发此错误的自定义格式或过滤器,请提供其隐含(或指向它的链接)以及完整的StackTrace,以识别错误源。
但是您永远不要调用Patch<object>
因为object
返回类型没有指定要反序列化为的响应类型。 由于您具有IReturn<T>
标记,因此只需发送请求DTO:
_jsonClient.Patch(new PartialTest { ... });
它将尝试在IReturn<PartialTestRequestResponse>
响应DTO中反序列化响应。 但是,当您的请求DTO实现IRequiresRequestStream
这IRequiresRequestStream
您期望的字节数不符合正常的请求DTO,在这种情况下,您可能希望使用HTTP Utils之类的原始HTTP客户端,例如:
var bytes = request.Url.SendBytesToUrl(
method: HttpMethods.Path,
requestBody: jsonPatchBytes,
contentType: "application/json-patch+json",
accept: MimeTypes.Json);
您可以使用请求过滤器修改JSON客户端的ContentType,例如:
_jsonClient.RequestFilter = req =>
req.ContentType = "application/json-patch+json";
但是使用像HTTP Utils这样的低级HTTP客户端来处理非JSON服务请求更为合适。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.