如何在apicontroller动作上返回403状态代码

时间:2016-04-19 15:38:57

标签: c# asp.net-mvc asp.net-web-api

我希望将返回类型保留为字符串,但希望响应代码为403。

这就是我现在所拥有的。

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

更新

我找到了下面的代码,但有没有另外一种方法没有抛出异常?

throw new HttpResponseException(HttpStatusCode.Unauthorized);

1 个答案:

答案 0 :(得分:1)

您可以在行动中投放HttpResponseException

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