【发布时间】:2020-09-14 12:11:53
【问题描述】:
我正在尝试从 Microsoft 示例开始制作 IdentityServer4。
该示例包含一个 Api 项目和一个 mcv 客户端,用于验证和调用 api。
Api 项目 Startup.cs:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
options.Authority = "http://localhost:5000";
options.RequireHttpsMetadata = false;
options.Audience = "api1";
});
}
public void Configure(IApplicationBuilder app)
{
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
Api IdentityController.cs:
namespace Api.Controllers
{
[Route("identity")]
[Authorize]
public class IdentityController : ControllerBase
{
public IActionResult Get()
{
return new JsonResult(from c in User.Claims select new { c.Type, c.Value });
}
}
}
MvcClient 中的这段代码正确调用了 IdentityController 的动作:
public async Task<IActionResult> CallApi()
{
var accessToken = await HttpContext.GetTokenAsync("access_token");
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var content = await client.GetStringAsync("http://localhost:5001/identity");
ViewBag.Json = JArray.Parse(content).ToString();
return View("json");
}
我向 IdentityController 添加了一个名为 Test 的操作:
namespace Api.Controllers
{
[Route("identity")]
[Authorize]
public class IdentityController : ControllerBase
{
public IActionResult Get()
{
return new JsonResult(from c in User.Claims select new { c.Type, c.Value });
}
public IActionResult Test()
{
return new JsonResult(from c in User.Claims select new { c.Type, c.Value });
}
}
}
但此代码在 McvClient 中找不到 404:
public async Task<IActionResult> CallTestApi()
{
var accessToken = await HttpContext.GetTokenAsync("access_token");
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var content = await client.GetStringAsync("http://localhost:5001/identity/Test");
ViewBag.Json = JArray.Parse(content).ToString();
return View("json");
}
【问题讨论】:
-
404,我认为你的服务器没有启动或端点不存在
-
服务器已启动,localhost:5001/identity 工作正常。但是如何调用另一个动作?
标签: c# .net-core asp.net-core-mvc identityserver4