简体   繁体   中英

Restsharp Patch request

I am using restsharp client. Trying to create patch request and update a couple of fields. This is my first experience working with restsharp. I am getting json parser error(The JSON patch document was malformed and could not be parsed).

I am able to do POST request without any issues.

Here is my code:

var client = new RestClient(RequestProperties.ClientUrl + @"Jobs?id=" + jobs.JobAccessId.ToString());    
var token = RequestProperties.Token;

client.AddDefaultHeader("Authorization", string.Format("Bearer {0}", token));

var request = new RestRequest(Method.PATCH) { RequestFormat = DataFormat.Json };

request.AddHeader("Postman-Token", token);
request.AddHeader("Cache-Control", "no-cache");
request.AddHeader("Content-Type", "application/json-patch+json");
request.AddJsonBody(new { op = "replace", path = "/shippedDate", value = jobs.ShippedDate });
request.AddJsonBody(new { op = "replace", path = "/statusdCode", value = jobs.StatusdCode.ToString() });

IRestResponse response = client.Execute(request);

There are several issues with this code:

  1. It is preferred to keep a single instance of the RestClient for one base URL. The base URL should not include any parameter values.
  2. We advise using AddQueryParameter to specify query parameters per request.
  3. You better use the JWT authorizer to give requests the bearer token rather than adding the header manually. It is also done on the client level.
  4. When using AddJsonBody , there's no need to add content type and request data type, it is all done automatically.
  5. Probably most importantly, you can only have one body parameter for any kind of request. It is not a RestSharp limitation, that's how HTTP works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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