1
我正在使用此代碼來使用ASP.NET MVC 5 WebAPI2。通過HttpClient登錄
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);
}
我需要通過用戶名和密碼,不知何故。任何線索?