Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return Response as string

Tags:

c#

restsharp

I am trying to return a String response from a POST request using RestSharp.

This is what I'm trying

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;
}

I am getting the following error

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

on this line

return response.Content;

How can I return a string response from RestSharp?

The response is a GUID String.

like image 395
AutoTester213 Avatar asked Aug 14 '26 23:08

AutoTester213


2 Answers

Either change the return type of PostNewLocation to string if you want to return raw content of the response as a string:

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

Or return response instead of response.Content if you want to return instance of IRestResponse (you can later get a raw content):

public IRestResponse PostNewLocation (
   ...
   return response;
}
like image 179
Sergey Berezovskiy Avatar answered Aug 16 '26 14:08

Sergey Berezovskiy


Your method is returning type IRestResponse.

Youre trying to return CONTENT, which is a string:

enter image description here

like image 28
Wjdavis5 Avatar answered Aug 16 '26 13:08

Wjdavis5



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!