Home > Net >  How to return a 401 with a custom message?
How to return a 401 with a custom message?

Time:08-13

In my Web API, I catch an AuthenticationException thrown by my DoCdssLoginTests(...) method I'm returning a 401 error in this case, but I'd like to be able to send a custom message with it.

The content member isn't available, and I can't override the response with a new one.
I found this thread, but nothing actually works in my method as I'm returning a string not an IHttpActionResult.

.NET exceptions I can throw for Not Authorized or Not Authenticated

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

CodePudding user response:

You have to return ActionResult and then you can return Unauthorized(); 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";
}
  • Related