有时获取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;
}
}
错误
发生了一个或多个错误。 ---&GT; System.AggregateException:一个或 发生了更多错误。 ---&GT; System.Threading.Tasks.TaskCanceledException:任务被取消 ---内部异常堆栈跟踪结束---在System.Threading.Tasks.Task.ThrowIfExceptional(布尔值 includeTaskCanceled Exceptions)at System.Threading.Tasks.Task
1.GetResultCore(Boolean waitCompletionNotification) at System.Threading.Tasks.Task
1.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);
}
}
启动类默认情况下无需更改
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);
}
}
有任何线索吗?
答案 0 :(得分:6)
很难说肯定,但你阻止HttpClient调用的方式无济于事。 HttpClient是一个仅支持异步的库;你可能遇到僵局。我建议删除所有.Result
和.Wait()
并使用async/await
异步写入所有内容。你的Task.Run什么都没有,所以应该去。
我知道这是从控制台应用程序移植的Topshelf应用程序。我对Topshelf不太熟悉,但我认为,就像控制台应用程序一样,你需要阻止某个地方,否则你的应用程序就会退出。这样做的地方就在最顶端 - 应用程序的入口点。
这演示了模式,并重写了GetApiToken
方法:
// app entry point - the only place you should block
void Main()
{
MainAsync().Wait();
}
// the "real" starting point of your app logic. do everything async from here on
async Task MainAsync()
{
...
var token = await GetApiTokenAsync(username, password, apiBaseUri);
...
}
async Task<string> GetApiTokenAsync(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
HttpResponseMessage responseMessage = await client.PostAsync("/Token", formContent);
var responseJson = await responseMessage.Content.ReadAsStringAsync();
var jObject = JObject.Parse(responseJson);
token = jObject.GetValue("access_token").ToString();
return token;
}
}