【发布时间】:2021-11-21 03:23:19
【问题描述】:
我有一种登录方法,如下所示:
public async Task<ActionResult> Index(LoginModel loginModel)
{
string url = "API_URL";
var response = await client.PostAsJsonAsync(url, loginModel);
if (response.IsSuccessStatusCode)
{
string result = await response.Content.ReadAsStringAsync();
var jsonData = JObject.Parse(result);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", "Bearer " + jsonData["accessToken"]);
return RedirectToAction("PostLogin");
}
else
{
ModelState.AddModelError("", "These credentials does not work. Hmm..");
}
return View(loginModel);
}
现在,如果用户成功登录,那么我将获得令牌,并且我将其设置在标题中。现在,我将用户重定向到 PostLogin 方法。
但在那种方法中,我无法访问该令牌。下面是代码。
public async Task<ActionResult> PostLogin()
{
var accessToken = await HttpContext.GetTokenAsync("accessToken"); // Here I can't see token. and getting value as per below.
return View();
}
即使我收到以下错误:
InvalidOperationException: No authenticationScheme was specified, and there was no DefaultAuthenticateScheme found. The default schemes can be set using either AddAuthentication(string defaultScheme) or AddAuthentication(Action<AuthenticationOptions> configureOptions).
【问题讨论】:
-
client变量在哪里定义? -
@AleksaRistic 在控制器顶部: public class LoginController : Controller { HttpClient client = new HttpClient();
-
看起来您还没有在
Startup类中配置默认身份验证方案,例如services.AddAuthentication(options => options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme) -
@MartinCostello 我做了这样的改变: public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); services.AddAuthentication(options => options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme); }
-
仍然出现同样的错误
标签: c# asp.net asp.net-core asp.net-web-api