通过HttpClient

时间:2016-04-14 17:01:53

标签: c# asp.net-web-api httpclient

我正在使用此代码来使用ASP.NET MVC 5 WebAPI2。

static async Task RunAsync()
        {
            using (var client = new HttpClient())
            {
               client.BaseAddress = new Uri("http://localhost:52967/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                // New code:
                HttpResponseMessage response = await client.GetAsync("api/Account/Login");
                if (response.IsSuccessStatusCode)
                {
                    var data = await response.Content.ReadAsStringAsync();

                }
            }
        }

AccountController下,我创建了以下方法

[HttpPost]
        [AllowAnonymous]
        [Route("Login")]
        public HttpResponseMessage Login(string username, string password)
        {
            try
            {
                var identityUser = UserManager.Find(username, password);

                if (identityUser != null)
                {
                    var identity = new ClaimsIdentity(Startup.OAuthOptions.AuthenticationType);
                    identity.AddClaim(new Claim(ClaimTypes.Name, username));

                    AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
                    var currentUtc = new SystemClock().UtcNow;
                    ticket.Properties.IssuedUtc = currentUtc;
                    ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(1440));

                    var token = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);

                    var response = new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content = new ObjectContent<object>(new
                        {
                            UserName = username,
                            ExternalAccessToken = token
                        }, Configuration.Formatters.JsonFormatter)
                    };

                    return response;


                }
            }
            catch (Exception)
            {
            }

            return new HttpResponseMessage(HttpStatusCode.BadRequest);
        }

我需要以某种方式传递用户名和密码。任何线索?

1 个答案:

答案 0 :(得分:2)

https://blogs.msdn.microsoft.com/martinkearn/2015/03/25/securing-and-securely-calling-web-api-and-authorize/

static async Task RunAsync()
{
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri("http://localhost:52967/");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        //setup login data
        var username = "support1@gmail1.com";
         var password = "Testing1!";
         var formContent = new FormUrlEncodedContent(new[]
         {
             new KeyValuePair<string, string>("grant_type", "password"),
             new KeyValuePair<string, string>("username", username),
             new KeyValuePair<string, string>("password", password),
         });
         //send request
         HttpResponseMessage responseMessage = await client.PostAsync("/Token", formContent);
         //get access token from response body
         var responseJson = await responseMessage.Content.ReadAsStringAsync();
         var jObject = JObject.Parse(responseJson);
         var token = jObject.GetValue("access_token").ToString();
     }
}