Maison  >  Questions et réponses  >  le corps du texte

Comment renvoyer le 401 avec un message personnalisé ?

Dans mon API Web, j'attrape l'AuthenticationException lancée par la méthode DoCdssLoginTests(...) auquel cas je renvoie une erreur 401, mais je souhaite pouvoir l'utiliser pour envoyer un message personnalisé. ≪ /p>

Le membre de contenu n'est pas disponible et je ne peux pas remplacer la réponse par un nouveau membre.

J'ai trouvé ce fil mais il ne fait vraiment rien dans ma méthode puisque je renvoie une chaîne au lieu d'un IHttpActionResult.

Je peux cibler les exceptions .NET levées pour "Non autorisé" ou "Non validé"

[ 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粉851401475292 Il y a quelques jours447

répondre à tous(1)je répondrai

  • P粉567281015

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

    ActionResult doit être renvoyé avant que Unauthorized() puisse être renvoyé comme ceci :

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

    répondre
    0
  • Annulerrépondre