search

Home  >  Q&A  >  body text

How to return 401 with custom message?

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粉851401475P粉851401475371 days ago501

reply all(1)I'll reply

  • P粉567281015

    P粉5672810152024-01-02 11:11:36

    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";
    }

    reply
    0
  • Cancelreply