I'm using RestSharp 107.1.3 and I'm struggling to correctly set the request headers. It worked in RestSharp 106.6.9, but since upgrading, the request fails with the message:
StatusCode: NotAcceptable, Content-Type: text/html, Content-Length: 1346)
and the content-type is always "text/html" which is wrong.
The returned HTML says 406 - Client browser does not accept the MIME type of the requested page
This is the code that worked with the old version of RestSharp but it isn't working in the new version:
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 );
This is what I'm attempting to use with the new version of RestSharp. The commented lines, in every possible combination, are my attempts to get it to work.
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 );
What am I doing wrong? I have read over the documentation several times, but I must still be missing something!
The AddXmlBody
method adds an object, which RestSharp will serialize to XML and send the serialized body. It doesn't suppose to be used with a pre-serialized payload.
If you want to send a pre-serialized string, you need to use AddStringBody(serializedString, contentType)
.
The AddStringBody
is just a wrapper of adding a new BodyParameter
instance:
public static RestRequest AddStringBody(this RestRequest request, string body, string contentType)
=> request.AddParameter(new BodyParameter("", body, Ensure.NotEmpty(contentType, nameof(contentType))));
You can use request.AddParameter(new BodyParameter(...))
if you need the body parameter to have a specific name.