以字符串形式返回响应

时间:2018-12-21 12:08:28

标签: 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;
}

我遇到以下错误

  

错误CS0029无法将类型'string'隐式转换为'RestSharp.IRestResponse'

在此行

return response.Content;

如何从RestSharp返回string响应?

响应是一个GUID字符串。

2 个答案:

答案 0 :(得分:4)

如果要以字符串形式返回响应的原始内容,请将PostNewLocation的返回类型更改为string

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

如果要返回response的实例,则返回response.Content而不是IRestResponse(以后可以获取原始内容):

public IRestResponse PostNewLocation (
   ...
   return response;
}

答案 1 :(得分:1)

您的方法返回的类型为IRestResponse。

您试图返回CONTENT,它是一个字符串:

enter image description here

相关问题