You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用RestSharp实现Postman中正常运行的text/plain格式PUT请求?

How to Send a text/plain Request Body with RestSharp

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?

  • AddStringBody is Your Friend: Introduced in RestSharp v107+, this method takes care of both setting the Content-Type: text/plain header and formatting your sessionId as the plain text body. No need to manually create a Parameter object anymore.
  • Cleaner URL Construction: Used string interpolation to build the resource URL more readably.
  • Explicit Success Check: Returns response.IsSuccessful which 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:41:17