如何返回帶有自訂訊息的 401?
P粉851401475
P粉851401475 2024-01-01 15:06:48
0
1
444

在我的 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粉851401475
P粉851401475

全部回覆(1)
P粉567281015

必須回傳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";
}
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!