Search code examples
c#asp.net-coreasp.net-core-identity

Authorization WebAPI behaving like MVC


I am using asp.core 2.1 to create web API's I have a controller like this

 [Route("api")]
 [ApiController]
 public class LessonController : ControllerBase
 {

    [HttpGet]
    [Route("lessons/{id}")]
    [Authorize(Roles = "Teacher")]
    public async Task<IActionResult> GetLesson(int id)
    {
      //....
    }
 }

With the [Authorize] attribute i just get the error below?

The default Identity UI layout requires a partial view '_LoginPartial' usually located at '/Pages/_LoginPartial' or....

As this is An API I'm confused as to why in the error it is looking for partial views?


Solution

  • The error message you refer to comes from ASP.NET Core Identity's Default UI (specifically, it's in the _Layout.cshtml page here). The Default UI is used when you use either of the following options in Startup.ConfigureServices:

    services.AddDefaultIdentity<User, Role>()
        ...
    

    -or-

    services.AddIdentity<User, Role>()
        .AddDefaultUI()
        ...
    

    If you don't want to use the Default UI, you'll need to avoid using AddDefaultIdentity and AddDefaultUI and just use AddIdentity<User, Role>.