如何用RestSharp实现Postman中正常运行的text/plain格式PUT请求?
Hey there, I can help you get that RestSharp request working with text/plain content type properly. Your current approach is heading in the right direction, but RestSharp has simpler, more reliable ways to handle plain text request bodies that avoid manual parameter setup.
Corrected Code Implementation
Here's the cleaned-up, working version of your method:
public bool CloseVisit(int visitDateId) { try { // Initialize the request with the correct URL and HTTP method var request = new RestRequest($"{Const.CloseVisitUrl}{visitDateId}", Method.Put); // Add the plain text body in one step—no need for manual Parameter objects request.AddStringBody(sessionId, ContentType.PlainText); // Execute the request (make sure you have an instance of RestClient, e.g., _restClient) var response = _restClient.Execute(request); // Return true if the request was successful (adjust based on your API's success criteria) return response.IsSuccessful; } catch (Exception ex) { // Handle any exceptions (log them, rethrow, etc.) Console.WriteLine($"Failed to close visit: {ex.Message}"); return false; } }
What's Different Here?
AddStringBodyis Your Friend: Introduced in RestSharp v107+, this method takes care of both setting theContent-Type: text/plainheader and formatting yoursessionIdas the plain text body. No need to manually create aParameterobject anymore.- Cleaner URL Construction: Used string interpolation to build the resource URL more readably.
- Explicit Success Check: Returns
response.IsSuccessfulwhich checks for HTTP 2xx status codes—adjust this if your API uses a different success indicator.
If You're Using an Older RestSharp Version (Pre-v107)
If you can't upgrade to the latest RestSharp, you can use the older AddParameter approach correctly:
// Replace the AddStringBody line with this request.AddParameter("text/plain", sessionId, ParameterType.RequestBody);
This will set the body content to sessionId with the text/plain content type.
Why Your Original Code Might Have Failed
Your code was cut off, but common issues with manual parameter setup include forgetting to finish the AddParameter call, or misconfiguring the parameter's type/content type. Using the dedicated methods like AddStringBody eliminates these easy-to-make mistakes.
Content of the question来源于stack exchange,提问作者piotrB

