how to return 401 in razor pages?

mc 4,111 Reputation points
2023-04-14T13:49:52.1333333+00:00

how to return status code in razor pages not redirect?

builder.Services.AddRazorPages().AddRazorPagesOptions(options =>
{
    options.Conventions.AuthorizeFolder("/");
    options.Conventions.AllowAnonymousToPage("/Login");
});

and I create a controller

[Authorize]
public class InfoController:ControllerBase
{
public string GetIndex()
{
     return "OOO";
}
}```

If I call the api it will redirect to /login and I want it return status code = 401 
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,400 questions
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Zhi Lv - MSFT 32,106 Reputation points Microsoft Vendor
    2023-04-17T03:12:48.81+00:00

    Hi @打玻璃

    If you are using Asp.net core identity or cookie authentication, to prevent the Web API redirect to the Login page and show the 401 error, you can override the Cookie Authentication's OnRedirectToLogin event:

    builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
    {
        options.Events.OnRedirectToAccessDenied =
        options.Events.OnRedirectToLogin = c =>
        {
            c.Response.StatusCode = StatusCodes.Status401Unauthorized;
            return Task.FromResult<object>(null);
        };
    });
    

    After that, when you access the protected action method (the user is not authenticated), it will show the 401 error. The result as below:
    User's image


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
    Best regards,
    Dillion

    1 person found this answer helpful.

  2. AgaveJoe 27,696 Reputation points
    2023-04-14T14:12:50.8133333+00:00

    The code is functioning as expected since InfoController is an MVC controller not Web API.
    Web API example.

        [Route("api/[controller]")]
        [ApiController]
        public class ValuesController : ControllerBase
        {
            // GET: api/<ValuesController>
            [HttpGet]
            public IActionResult Get()
            {
                return Unauthorized();
            }
    

  3. AgaveJoe 27,696 Reputation points
    2023-04-14T17:13:51.1966667+00:00

    please add [Authorize] and it redirect not return unauthorized.

    Correct! That's how MVC controller fundamentally work. MVC controller redirect to a login page when the request is not authorized because MVC is a framework for creating user interfaces. The login page lets the user know they need to login.

    A Web API controller returns a 401 since there is no user interface. The 401 lets the caller know the request was not authorized. Create a Web API controller rather than an MVC controller if you want this behavior. Keep in mind, tokens are used to authorize Web API requests while MVC uses an authentication cookie.

        [Route("api/[controller]")]
        [ApiController]
        public class ValuesController : ControllerBase
        {
            // GET: api/<ValuesController>
            [HttpGet]
            [Authorize]
            public IActionResult Get()
            {
                return Ok("Hello World");
            }
    

    If you want to change the behavior of MVC then write a custom authorize attribute or filter. Please read the official documentation. Introduction to authorization in ASP.NET Core