簡體   English   中英

如何在apicontroller操作上返回403狀態代碼

[英]how to return a 403 status code on apicontroller action

我想將返回類型保留為字符串,但希望響應代碼為403。

這就是我目前所擁有的。

[HttpGet]
public string test(string echoText)
{
    // Not authorized
    if (echoText == "403")
    {
        StatusCode(HttpStatusCode.Forbidden);
        return "";
    }
    else
        return echoText;
}

更新

我找到了以下代碼,但是還有另一種不引發異常的方法嗎?

throw new HttpResponseException(HttpStatusCode.Unauthorized);

您可以在操作中拋出HttpResponseException

[HttpGet]
public string test(string echoText)
{
    // Not authorized
    if (echoText == "403")
    {
        throw new HttpResponseException(HttpStatusCode.Forbidden);
    }
    else
        return echoText;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM