示例#1
0
        internal async Task <ServiceResult> Autenticar(string pUsuario, string pSenha)
        {
            var _serviceResult = new ServiceResult();

            try
            {
                var _args = new FormUrlEncodedContent(new List <KeyValuePair <string, string> >()
                {
                    new KeyValuePair <string, string>("grant_type", "password"),
                    new KeyValuePair <string, string>("username", pUsuario),
                    new KeyValuePair <string, string>("password", pSenha),
                });

                using (var _response = await this._HttpClient.PostAsync("/token", _args))
                {
                    if (!_response.IsSuccessStatusCode)
                    {
                        throw new InvalidOperationException();
                    }

                    var _responseContent = await _response.Content.ReadAsStringAsync();

                    if (string.IsNullOrWhiteSpace(_responseContent))
                    {
                        throw new InvalidOperationException();
                    }

                    var _token = JsonConvert.DeserializeObject <TokenResult>(_responseContent);

                    this._HttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(_token.token_type, _token.access_token);
                }
            }
            catch (Exception ex) { _serviceResult.AddException(ex); }

            return(_serviceResult);
        }