简体   繁体   English

是否可以或必须设置ServiceStack客户端删除请求的内容类型?

[英]Is it possible or necessary to set the content type of a ServiceStack client delete request?

I have the following code. 我有以下代码。

public T SendUpdateRequest(string url)
{
    using (JsonServiceClient client = new JsonServiceClient())
    {
        T response = client.Put<T>(url);
        return response;
    }
}

I have similar methods for create and delete requests, calling the JsonServiceClient Post and Delete methods respectively. 我有类似的创建和删除请求方法,分别调用JsonServiceClient PostDelete方法。

When calling my update or create methods, the call to the external API works fine. 调用我的更新或创建方法时,对外部API的调用工作正常。 Delete does not. 删除没有。 I can see that the API's delete method does indeed work if I fire a request to it via REST console . 我可以看到,如果我通过REST控制台向它发出请求,那么API的delete方法确实有效。

When I compare my non-working delete with the working one's request/response in Fiddler, I can see the main difference is my request is not setting content-type to application/json (all these methods return JSON). 当我将我的非工作删除与Fiddler中的工作请求/响应进行比较时,我可以看到主要的区别是我的请求是没有将content-type设置为application/json (所有这些方法都返回JSON)。

My question is, is it possible (or even necessary) to explicitly set the content-type of my delete request to application/json in order to successfully call my API method? 我的问题是,为了成功调用我的API方法,是否有可能(甚至有必要)将我的删除请求的content-type显式设置为application/json

The ServiceStack clients do not set the content-type header on requests where there is no request body, as the content-type only applies to the body, and is therefore redundant. ServiceStack客户端不在没有请求主体的请求上设置content-type标头,因为content-type仅适用于主体,因此是多余的。

This can be seen here in the code that prepares the client request. 可以在准备客户端请求的代码中看到

if (httpMethod.HasRequestBody())
{
    client.ContentType = ContentType;
    ...

A correctly implemented RESTful service should be happy with a DELETE request without content-type being specified where there is no body. 正确实现的RESTful服务应该满足于DELETE请求,而没有在没有正文的情况下指定content-type

DELETE /User/123 HTTP/1.1

If the service you are calling is not happy with your request without this type being specified (which is unusual) , then you can manually enforce the sending of the type using this filter: 如果您正在调用的服务对您的请求不满意而未指定此类型(这是不常见的) ,那么您可以使用此过滤器手动强制发送类型:

var client = new JsonServiceClient("https://service/");
client.RequestFilter += (httpReq) => {
    // Force content type to be sent on all requests
    httpReq.ContentType = "application/json";
};

I hope that helps. 我希望有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM