BaseHost URL setting in RestSharp

Viewed 77

I am using the latest version of RestSharp. I am wanting to set the Base URL so i can change it at a later date but only the domain would change and lower level URLs would always remain the same. Example

www.example.com/api/customers

www.example.com/api/customers/1

would become

www.newdomain.com/api/customers

www.newdomain.com/api/customers/1

Using this code works

 var rest = new RestClient();
 rest.Options.BaseUrl = new Uri("https://www.example.com/api/customers/");
 var restReq = new RestRequest();
 RestResponse resp = rest.Execute<CustomerModel>(restReq);

I tried to change the above code to (setting the BaseHost)

 var rest = new RestClient();
 rest.Options.BaseHost = "https://www.example.com";// Will move this to a config later
 rest.Options.BaseUrl = new Uri("/api/customers/");
 var restReq = new RestRequest();
 RestResponse resp = rest.Execute<CustomerModel>(restReq);

but receive the standard error about the URI not being in the correct format.

I know i can use something like Path.Combine(baseDomain,rest.Options.BaseUrl) but then it leaves me wondering why the second posted code doesnt work when setting the BaseHost?

I couldnt find anything on the documentation to explain this either?

1 Answers

You should may want to use RestSharp like this:

var rest = new RestClient("https://www.example.com");
var restReq = new RestRequest("/api/customers/");
RestResponse resp = rest.ExecuteAsync<CustomerModel>(restReq);

This way you set the BaseURL on 1st line, and then on the 2nd you set the path of your API, which should not change.

Related