2016-12-01 34 views
0

我試圖按如下方式執行與JsonServiceClient補丁到服務棧API:內容類型必須是「應用/ JSON-補丁+ JSON」 JsonServiceClient ServiceStack

var patchRequest = new JsonPatchRequest 
{ 
    new JsonPatchElement 
    { 
     op = "replace", 
     path = "/firstName", 
     value = "Test" 
    } 
}; 
_jsonClient.Patch<object>($"/testurl/{id}", patchRequest); 

但我發現了出現以下錯誤:

Content-Type must be '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庫。

+0

這不是ServiceStack中的錯誤,請更新您的帖子以包含ServiceStack服務實現。 – mythz

回答

1

由於它不是ServiceStack中的錯誤,因此仍不清楚Exception的來源。如果您註冊了自定義格式或過濾器會引發此錯誤,請包含其impl(或其鏈接)以及可識別錯誤來源的完整StackTrace。

但是,您絕對不應該撥打Patch<object>作爲object返回類型不指定要反序列化的響應類型。既然你有一個IReturn<T>標記,你可以只發送請求DTO:

_jsonClient.Patch(new PartialTest { ... }); 

這將嘗試反序列化在IReturn<PartialTestRequestResponse>響應DTO的響應。但是,隨着您的要求DTO實現IRequiresRequestStream它說你期待未知的字節是不符合正常的請求DTO,在這種情況下,你可能要使用原始HTTP客戶端就像HTTP Utils,如:

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客戶端(如HTTP)utils的非JSON服務請求是這樣的。

+0

你是對的,這是一個拋出錯誤的自定義類型請求過濾器,不是SeviceStack –

+1

這個過濾器正在驗證requestDTO,它實現了接口IJsonPatchDocumentRequest,而不是SeviceStack。最後我用Http Util string.SendStringToUr發送請求。非常感謝您的幫助! –

相關問題