How to return 401 with custom message?
P粉851401475
P粉851401475 2024-01-01 15:06:48
0
1
520

In my Web API, I'm catching the AuthenticationException thrown by the DoCdssLoginTests(...) method in which case I'm returning a 401 error, but I want to be able to use it to send a custom message. < /p>

The content member is not available and I cannot overwrite the response with a new member.

I found this thread but it doesn't really do anything in my method since I'm returning a string instead of an IHttpActionResult.

Can I target .NET exceptions thrown for "Unauthorized" or "Unauthenticated"

[ HttpGet ]
[ Route( "/DoCdssLoginTests" ) ]
public string DoCdssLoginTests( string sAdName )
{
    log.LogTrace( "AdStudentController::DoCdssLoginTests() - in" );
   
    try
    { 
        return studBll.DoCdssLoginTests( sAdName );
    }
    catch ( AuthenticationException ex )
    {
        Response.StatusCode = ( int ) HttpStatusCode.Unauthorized;
        //<--- I WANT TO SET A CUSTOM MESSAGE HERE TO BE RETURNED TO VUE CLIENT. - EWB
        return "N";
    }
    catch ( Exception ex )
    {
        throw;
    }

    return "OK";
}


P粉851401475
P粉851401475

reply all(1)
P粉567281015

ActionResult must be returned before Unauthorized() can be returned; like this:

public ActionResult<string> DoCdssLoginTests(string sAdName)
{
    log.LogTrace("AdStudentController::DoCdssLoginTests() - in");
    try
    {
        return studBll.DoCdssLoginTests(sAdName);
    }
    catch (AuthenticationException ex)
    {
        return Unauthorized("Your custom message");
    }
    catch (Exception ex)
    {
        throw;
    }
    return "OK";
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template