如何返回带有自定义消息的 401?
P粉851401475
P粉851401475 2024-01-01 15:06:48
0
1
437

在我的 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学习者快速成长!