コード例 #1
0
ファイル: Program.cs プロジェクト: erpnet/DomainApi
        static async Task ExecuteSamples(string sampleName, Uri root, string user, string pass)
        {
            var credentials = new ErpCredentials("Samples", user, pass, "en");

            Console.WriteLine("Logging in...");
            using (var session = new ErpSession(root))
            {
                await session.LoginAsync(credentials);

                // Omit null values from JSON result.
                session.RequestOptions.SkipNulls = true;

                await ExecuteSample(sampleName, session);
            }
        }
コード例 #2
0
ファイル: ErpSession.cs プロジェクト: erpnet/DomainApi
        /// <summary>
        /// Logins the specified user.
        /// </summary>
        /// <param name="credentials">The credentials.</param>
        /// <returns></returns>
        /// <exception cref="Exception">Invalid user name or password.</exception>
        public async Task <string> LoginAsync(ErpCredentials credentials)
        {
            StringContent content = new StringContent(
                string.Format("{{\"app\":\"{0}\",\"user\":\"{1}\",\"pass\":\"{2}\",\"ln\":\"{3}\"}}",
                              credentials.ApplicationName,
                              credentials.UserName,
                              credentials.Password,
                              credentials.Language));

            content.Headers.ContentType.MediaType = "application/json";
            var uri = ServiceRoot.ToString().Replace("/odata", "/Login").TrimEnd('/');

            HttpRequestMessage msg = new HttpRequestMessage()
            {
                RequestUri = new Uri(uri),
                Method     = HttpMethod.Post,
                Content    = content
            };

            msg.Headers.ExpectContinue = false;

            var result = await httpClient.SendAsync(msg, HttpCompletionOption.ResponseContentRead);

            var json = await result.Content.ReadAsStringAsync();

            try
            {
                if (!result.IsSuccessStatusCode)
                {
                    throw new Exception(json);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Invalid user name or password.", ex);
            }


            authorizationHeader = json.Split(':')[1].Trim('"', '}');
            httpClient.DefaultRequestHeaders.Add("Authorization", authorizationHeader);
            return(json);
        }