【发布时间】:2016-04-29 11:35:25
【问题描述】:
获取 ASP.NET MVC5 WebAPI 令牌有时会失败
代码
string GetAPITokenSync(string username, string password, string apiBaseUri)
{
var token = string.Empty;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(apiBaseUri);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.Timeout = TimeSpan.FromSeconds(60);
//setup login data
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
Task t = Task.Run(() =>
{
HttpResponseMessage responseMessage = client.PostAsync("/Token", formContent).Result;
var responseJson = responseMessage.Content.ReadAsStringAsync().Result;
var jObject = JObject.Parse(responseJson);
token = jObject.GetValue("access_token").ToString();
});
t.Wait();
t.Dispose();
t = null;
GC.Collect();
return token;
}
}
错误
发生了一个或多个错误。 ---> System.AggregateException:一个或 发生了更多错误。 ---> System.Threading.Tasks.TaskCanceledException:任务已取消。
--- 内部异常堆栈跟踪结束 --- 在 System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceled 异常)在 System.Threading.Tasks.Task1.GetResultCore(Boolean waitCompletionNotification) at System.Threading.Tasks.Task1.get_Result()
WebAPi 登录方式默认没有变化。
[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);
}
}
Startup 类默认没有变化
public partial class Startup
{
public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }
public static string PublicClientId { get; private set; }
public void ConfigureAuth(IAppBuilder app)
{
// Configure the db context and user manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Configure the application for OAuth based flow
PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
// In production mode set AllowInsecureHttp = false
AllowInsecureHttp = true
};
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(OAuthOptions);
}
}
有什么线索吗?
【问题讨论】:
-
不是超时了吗? 60秒后?你为什么要在一个任务上运行 Post?然后阻塞你的调用线程等待任务完成?
-
@BrunoGarcia 我猜 60 秒就可以拿到令牌了。请提出一些需要考虑的建议...谢谢!
-
我的意思是:问题不是因为您的通话超时了吗?是因为它无法到达服务器还是需要太长时间(超过 60 秒)才能完成?特别是如果它有时只会失败
-
@BrunoGarcia 它应该可以工作......我也会尝试这个解决方案stackoverflow.com/questions/30656795/…
-
@Dimi 我认为您没有回答是否超时的问题。是吗?
标签: c# .net asp.net-mvc-5 httpclient token