首页  >  问答  >  正文

如何返回带有自定义消息的 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 天前441

全部回复(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
  • 取消回复