我有几个问题,我是否正在尝试实现一种安全的方法来为我的所有Web api调用保留令牌。我正在关注教程Here。这是我执行或未执行的问题
这是我使用IHelper调用学生api的方式,但是我在阅读异步数据时遇到问题。
public class StudentsController : Controller { private IApiHelper apiClient; public StudentsController(IApiHelper _helper) { apiClient = _helper; } // GET: Students public ActionResult Index() { return View(); } public ActionResult GetStudents() { List<StudentModel> listStudent = new List<StudentModel>(); var responseTask = apiClient.GetAsync("Students"); responseTask.Wait(); var result = responseTask.Result; if (result.IsSuccessStatusCode) { var readTask = result.Content.ReadAsAsync<List<StudentModel>>(); readTask.Wait(); listStudent = readTask.Result; } else { throw new Exception(result.ReasonPhrase); } return Json(listStudent, JsonRequestBehavior.AllowGet); } }
这基本上是我在IApiHelper上实现的。
My interface public interface IApiHelper { Task<AuthenticatedUser> Authenticate(string username, string password); }
这是实现
public class ApiHelper : IApiHelper
{
private HttpClient apiClient;
public ApiHelper()
{
InitializeClient();
}
public void InitializeClient()
{
string ApiBaseUrl = ConfigurationManager.AppSettings["api"];
apiClient = new HttpClient();
apiClient.BaseAddress = new Uri(ApiBaseUrl);
apiClient.DefaultRequestHeaders.Accept.Clear();
apiClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
public async Task<AuthenticatedUser> Authenticate(string username, string password)
{
var data = new FormUrlEncodedContent(new[] {
new KeyValuePair<string, string>("grant_type", "password"),
new KeyValuePair<string, string>("username", username),
new KeyValuePair<string, string>("password", password)
});
using (HttpResponseMessage response = await apiClient.PostAsync("/Token", data))
{
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsAsync<AuthenticatedUser>();
return result;
}
else
{
throw new Exception(response.ReasonPhrase);
}
}
}
}
我有几个问题,我是否正在尝试实现一种安全的方法来为我的所有Web api调用保留令牌。我在这里关注教程。这是我已实现或未能实现的问题...
问题与Autofac,DI或单例无关,与您的界面定义有关。根据您发布的内容,您的界面是: