c# - 以字符串形式返回响应

标签 c# api restsharp

我正在尝试使用 RestSharp 从 POST 请求返回字符串响应。

这就是我想要的

public IRestResponse PostNewLocation(string Name, string Type, Nullable<Guid> ParentId, string Location)
{
    object tmp = new
    {
        name = Name,
        type = Type,
        parentId = ParentId,
        Location = Location
    };
    string json = JsonConvert.SerializeObject(tmp);

    var Client = new RestClient();
    Client.BaseUrl = new Uri(BaseURL);
    var request = new RestRequest(Method.POST);
    request.Resource = string.Format("/Sample/URL?");
    request.AddParameter("application/json", json, ParameterType.RequestBody);
    IRestResponse response = Client.Execute(request);

    Console.Write(response.Content);

    if (!IsReturnedStatusCodeOK(response))
    {
        throw new HttpRequestException("Request issue -> HTTP code:" + response.StatusCode);
    }

    return response.Content;
}

我收到以下错误

Error CS0029 Cannot implicitly convert type 'string' to 'RestSharp.IRestResponse'

在这条线上

return response.Content;

如何从 RestSharp 返回一个 string 响应?

响应是一个 GUID 字符串。

最佳答案

如果您想将响应的原始内容作为字符串返回,请将 PostNewLocation 的返回类型更改为 string:

public string PostNewLocation (
   ...
   return response.Content;
}

或者返回 response 而不是 response.Content 如果你想返回 IRestResponse 的实例(你可以稍后获得原始内容):

public IRestResponse PostNewLocation (
   ...
   return response;
}

关于c# - 以字符串形式返回响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53884580/

相关文章:

c# - 迭代枚举类型

c# - 如何使用 C# WPF 打开 chm 文件中的特定页面

java - 使用 cookie 和内容类型 Text/plain 的放心发布请求

c# - 创建防火墙规则以在 C# 中以编程方式打开每个应用程序的端口

c# - 如何在 C# 中获取 OAuth 2.0 身份验证 token

c# - 'RestClient' 不包含 'JsonSerializer' 的定义并且没有扩展方法 'JsonSerializer'

c# - 如何将异步事件转发给父类?

c# - 如何在 vs 代码中生成具有文件范围命名空间语法(C#10)的类?

android - API:授权失败谷歌地图(黑屏)

c# - Visual-Studio 2013 中的 RestSharp 安装问题