使用 c# Web Api 2,我的代码会抛出InvalidOperationException
. 返回状态码 302 时,如何使用HandleException
注解为重定向提供位置?
[HandleException(typeof(InvalidOperationException), HttpStatusCode.Found, ResponseContent = "Custom message 12")]
public IHttpActionResult GetHandleException(int num)
{
switch (num)
{
case 12: throw new InvalidOperationException("DONT SHOW invalid operation exception");
default: throw new Exception("base exception");
}
}
编辑:对不起,我有点匆忙地问了这个问题。上面的类使用了一个继承自 ExceptionFilterAttribute 的 HandleExceptionAttribute 类。当我尝试调试他们的单元测试时,我没有意识到这一点。该问题不会出现在单元测试中,但会使用需要重定向 url 的 Visual Studio .webtest 出现。从 ExceptionFilterAttribute 继承的类未提供允许提供重定向 URL 的参数。抱歉问题不完整,感谢您花时间回答。
/// <summary>
/// This attribute will handle exceptions thrown by an action method in a consistent way
/// by mapping an exception type to the desired HTTP status code in the response.
/// It may be applied multiple times to the same method.
/// </summary>
[AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = true)]
public sealed class HandleExceptionAttribute : ExceptionFilterAttribute
{