问题
I'm writing a simple REST client for a C# WinForm application. I use RestSharp to make sending requests and getting responses easier. I have a few questions regarding how I should design my client.
The user interacts with the client only once. He pushes a Button
and the client is instantiated and passed to private
methods to do some logic in the background. It accesses objects from the server and synchronizes them with objects in the user's internal database.
The point is that the client's methods are accessed by private
methods called following the user's single action in the GUI. He does not have any control over which of the client's methods are called, and in which order.
So my questions are:
Can I ask the server for a token only once when I instantiate my client, and then store it in the client instance for future reference in the client's following requests? The token is a hash of the username and password, so it should not change over time. Of course, once I create a new instance of the client, it will again ask the server for a token.
Is it okay to keep a single
Request
object instance in my client? I can then set request header only once and all the methods that access the API will only need to change the request's resource URL and HTTP method. It would reduce repetitiveness in my code.
For example:
public PriceListItem[] GetPriceListItems()
{
string requestUrl = Resources.PriceListItemsUrl;
var request = new RestRequest(requestUrl, Method.GET);
request.AddHeader("SecureToken", _token);
var response = Client.Execute(request) as RestResponse;
JObject jObject = JObject.Parse(response.Content);
var priceListItems = jObject["Data"].ToObject<PriceListItem[]>();
return priceListItems;
}
I have quite a few methods for utilizing different resource URLs, but all have the same header. If I keep only one Request
instance in my client I can set the header only once. Is this approach okay? I would like to avoid any delegates and events.
回答1:
You have to use ParameterType.HttpHeader parameter
:
request.AddParameter("Authorization", "data", ParameterType.HttpHeader);
回答2:
It's perfectly normal to save auth token on client, as long it's encrypted and have expired time on it. You can improve it with implement session on your REST API, so you just need check if the auth token is still valid or not, and do the authentication if it's not valid.
Clearly you need to manage the way you request to the REST API, I Recommend you to use IDisposable Pattern for this manner, you can utilize some lazy implementation or Singelton.
来源:https://stackoverflow.com/questions/24903454/is-single-request-object-instance-in-rest-client-okay