Show/Hide Toolbars

Руководство администратора

Пример (C#): получение чатов для пользователя при forms-аутентификации

Ссылки Назад Вверх Вперед

warning_icon   В примере используются библиотеки JsonRules.dll и FirstFormJsonObjects.dll.

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
 
namespace TCClassLib.Test.ReadOnly.JsonStructureTest {
 
  public class JsonStructureTest {
    static FFClient client = null;
    static FFClient Client {
         get {
            if (client == null) {
               client = new FFClient(Settings.FFUrl);
               client.Login(Settings.FFLogin, Settings.FFPassword);
            }
            return client;
         }
     }
 
    public void GetMyChats_Call() {
        var jChats = Client.Post(DataService.GetMyChats, JObject.Parse("{\"openedChatId\":null}"));
        new FirstFormJsonObjects.Responses.Chats().Check(jChats);
     }
  }
 
  public class FFClient {
    public string BaseFFUrl {
        get;
        private set;
     }
     CookieCollection cookies = new CookieCollection();
 
    public FFClient(string baseFFUrl) {
        BaseFFUrl = baseFFUrl;
     }
 
    public JObject Login(string login, string password) {
        var url = "iOSClientServices/Auth.ashx";
        var content = new FormUrlEncodedContent(new Dictionary < string, string > {
           {
              "UserName",
              login
           },
           {
              "Pass",
              password
           }
        });
 
        var result = PostRequestHelper < string > (url, content, async response => {
           string res = await response.Content.ReadAsStringAsync();
          return res;
        }).Result;
 
        bool isError = false;
 
        try {
          new FirstFormJsonObjects.Responses.AuthError().Check(result);
           isError = true;
        } catch (JsonRules.RuleException) {}
 
        if (isError) {
          throw new Exception(result.ToString());
        }
 
        return result;
     }
 
    public JObject Post(string url, object pars) {
        var result = PostRequestHelper < string > (url, pars, async response => {
            string res = await response.Content.ReadAsStringAsync();
            return res;
        }).Result;
 
        return result;
     }
 
     string RemoveAspNetDProperty(string response) {
        if (!string.IsNullOrWhiteSpace(response)) {
          const string dPropertyPrefix = "{\"d\":";
          if (response.StartsWith(dPropertyPrefix)) {
              response = response.Substring(dPropertyPrefix.Length, response.Length — dPropertyPrefix.Length — 1);
           }
        }
        return response;
     }
 
     async Task < JObject > PostRequestHelper < T > (string requestUri, object content, Func < HttpResponseMessage, Task < T >> handleResult) {
        var handler = new HttpClientHandler();
 
        handler.CookieContainer = new CookieContainer();
 
        using(handler) {
           using(var client = new HttpClient(handler)) {
              client.BaseAddress = new Uri(BaseFFUrl);
 
              if (cookies != null) {
                 handler.CookieContainer.Add(client.BaseAddress, cookies);
              }
 
              client.DefaultRequestHeaders.Accept.Clear();
              client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
 
              HttpResponseMessage response = null;
              if (content is HttpContent) {
                 response = await client.PostAsync(requestUri, (HttpContent) content);
              } else {
                 response = await client.PostAsJsonAsync(requestUri, content);
              }
 
              cookies = handler.CookieContainer.GetCookies(client.BaseAddress);
 
              if (response.IsSuccessStatusCode) {
                 string res = await response.Content.ReadAsStringAsync();
                 res = RemoveAspNetDProperty(res);
                return JObject.Parse(res);
              } else {
                 string res = await response.Content.ReadAsStringAsync();
                throw new Exception(res);
              }
           }
        }
     }
  }
}

Полезные ссылки