设置 RestSharp Content-Type application/atom+xml;type=entry

Set RestSharp Content-Type application/atom+xml;type=entry

我正在使用 RestSharp 107.1.3,但我很难正确设置请求 headers。它在 RestSharp 106.6.9 中工作,但自升级以来,请求失败并显示消息:

StatusCode: NotAcceptable, Content-Type: text/html, Content-Length: 1346)

并且 content-type 始终是“text/html”,这是错误的。

返回的HTML表示406 - Client browser does not accept the MIME type of the requested page

这是适用于旧版本 RestSharp 但不适用于新版本的代码:

RestClient client = new RestClient( appSettings.BaseURL )
{
    Authenticator = new HttpBasicAuthenticator( appSettings.User, appSettings.Password )
};

RestRequest request = new RestRequest( "GL_GeneralJournalHeaderSPECIAL", Method.POST );
request.AddHeader( "Accept", "application/atom+xml;type=feed" );
request.Parameters.Clear();
request.AddParameter( "application/atom+xml;type=entry", sdata, ParameterType.RequestBody );
request.AddXmlBody( sdata );
request.RequestFormat = DataFormat.Xml;

IRestResponse response = await client.ExecuteTaskAsync( request );

这就是我尝试与新版本的 RestSharp 一起使用的内容。在每一种可能的组合中,注释行都是我尝试让它工作的尝试。

var options = new RestClientOptions()
{
    BaseUrl = new Uri( appSettings.SaBaseUrl ),
    RemoteCertificateValidationCallback = ( sender, certificate, chain, sslPolicyErrors ) => true

};
var client = new RestClient( options )
{
    Authenticator = new HttpBasicAuthenticator( appSettings.UserName, appSettings.Password ),
};
//client.AddDefaultHeader( KnownHeaders.Accept, "application/atom+xml;type=entry" );

var request = new RestRequest( "GL_GeneralJournalHeaderSPECIAL", Method.Post )
{
    RequestFormat = DataFormat.Xml
};
// request.AddHeader( "Accept", "application/atom+xml;type=entry" );
//request.AddHeader( "Content-Type", "application/atom+xml;type=entry" );
// request.AddBody( transaction.SData );
//request.AddXmlBody( transaction.SData );
request.AddParameter( "application/atom+xml;type=entry", transaction.SData, ParameterType.RequestBody );

var response = await client.ExecuteAsync( request );

我做错了什么? the documentation 看了好几遍,还是漏了点什么!

AddXmlBody 方法添加了一个对象,RestSharp 会将其序列化为 XML 并发送序列化的正文。它不应该与 pre-serialized 有效负载一起使用。

如果要发送pre-serialized字符串,需要使用AddStringBody(serializedString, contentType).

AddStringBody 只是添加新 BodyParameter 实例的包装器:

public static RestRequest AddStringBody(this RestRequest request, string body, string contentType)
    => request.AddParameter(new BodyParameter("", body, Ensure.NotEmpty(contentType, nameof(contentType))));

如果你需要body参数有一个特定的名字,你可以使用request.AddParameter(new BodyParameter(...))