Is single Request object instance in REST client okay?

醉酒当歌 提交于 2020-01-05 12:30:52

问题


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:


  1. 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.

  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!