Does RestSharp overwrite manually set Content-Type?

前端 未结 2 1066
感情败类
感情败类 2020-12-30 03:34

I\'m creating a RestSharp.RestRequest via:

RestRequest request = new RestRequest();
request.Method = Method.POST;
request.Resource = \"/rest-uri\";

request.         


        
相关标签:
2条回答
  • 2020-12-30 03:57

    It is possible changing Content-Type when you set the body content. The NAME parameter for Body sets the Content-Type.

    oRequest.Parameters.Add(new Parameter() { Name = "application/json;charset=UTF-8", Type = ParameterType.RequestBody, Value = sBody });
    
    0 讨论(0)
  • 2020-12-30 04:04

    svick's comment is right. Set the content type in the first parameter of AddParameter() and you can leave out the AddHeader() call.

    While that's the 'right' answer, I'll explain why it has a confusing method for doing this that's not exactly obvious.

    The intended way to accomplish this is to use AddBody() along with RestRequest.RequestFormat. An example:

    var client = new RestClient();
    // client.XmlSerializer = new XmlSerializer(); // default
    // client.XmlSerializer = new SuperXmlSerializer(); // can override with any implementaiton of ISerializer
    
    var request = new RestRequest();
    request.RequestFormat = DataFormat.Xml;
    request.AddBody(objectToSerialize);
    

    The serialization of objectToSerialize is based on the registered XmlSerializer. If you use RequestFormat = DataFormat.Json, then the RestClient.JsonSerializer is used. Implementations of ISerializer (which you can use to override the default serialization) declare their own Content-Types which is what gets passed through the janky AddParameter() overload you're using.

    AddParameter(contentType, content, ParameterType.RequestBody) was never meant to be called directly. It was added as a workaround to pass though data from AddBody() but then other things became dependent on it so it stuck around. It was a terrible decision in hindsight but it's too late to change it in the 1xx version line. If I ever build another version I'll make this more obvious.

    0 讨论(0)
提交回复
热议问题