首頁  >  問答  >  主體

如何返回帶有自訂訊息的 401?

在我的 Web API 中,我捕獲了 DoCdssLoginTests(...) 方法拋出的 AuthenticationException 在這種情況下我返回 401 錯誤,但我希望能夠使用它發送自訂訊息。 < /p>

內容成員不可用,我無法用新成員覆蓋回應。

我找到了這個線程,但在我的方法中實際上沒有任何作用,因為我返回的是字串而不是 IHttpActionResult。

我可以針對「未授權」或「未驗證」拋出的 .NET 例外狀況

[ 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 天前448

全部回覆(1)我來回復

  • P粉567281015

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

    必須回傳ActionResult,然後才能回傳Unauthorized();像這樣:

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

    回覆
    0
  • 取消回覆