UnauthorizedResponse
Namespace: RA.Utilities.Api.Results
The UnauthorizedResponse class is a specialized model for creating standardized 401 Unauthorized responses.
It is used when the request requires user authentication.
It inherits from Response<T>, with the Result property typed as an ErrorResult object.
🎯 Purpose
The UnauthorizedResponse class is a specialized model for creating standardized 401 Unauthorized API responses.
It is used to signal that the request lacks valid authentication credentials for the target resource.
Its primary functions are:
-
Standardizes Authentication Errors: It ensures that every
401 Unauthorizederror response has the exact same structure. -
Reduces Boilerplate: It automatically sets the response properties for an unauthorized request:
- ResponseCode: Set to
401(fromBaseResponseCode.Unauthorized). - ResponseType: Set to
ResponseType.Unauthorized. - ResponseMessage: Defaults to
"The request requires user authentication."(fromBaseResponseMessages.Unauthorized).
- Provides Structured Context: It can include an
ErrorResultpayload to provide specific details about why the authentication failed (e.g., "Invalid token", "Token expired").
⚙️ How It Works
When you create an instance of UnauthorizedResponse, it pre-configures the following properties:
ResponseCode: Set to401(fromBaseResponseCode.Unauthorized).ResponseType: Set toResponseType.Unauthorized.ResponseMessage: Defaults to"The request requires user authentication.".Result: An optionalErrorResultobject containing the error code and message.
🚀 Usage in a Controller
You can use this class in your controller actions or middleware when authentication fails.
using Microsoft.AspNetCore.Mvc;
using RA.Utilities.Api.Results;
[ApiController]
[Route("api/[controller]")]
public class ProfileController : ControllerBase
{
[HttpGet]
public IActionResult GetProfile()
{
if (!User.Identity.IsAuthenticated)
{
return Unauthorized(new UnauthorizedResponse(new ErrorResult
{
ErrorCode = "Unauthorized",
ErrorMessage = "User is not authenticated."
}));
}
return Ok(new SuccessResponse<UserProfile>(_service.GetProfile(User)));
}
}
Example JSON Output
{
"responseCode": 401,
"responseType": "Unauthorized",
"responseMessage": "The request requires user authentication.",
"result": {
"errorCode": "Unauthorized",
"errorMessage": "User is not authenticated."
}
}