【发布时间】:2016-06-05 19:47:12
【问题描述】:
使用 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
{
【问题讨论】:
-
HandleException 属性是你自己的?您能否提供源代码或源链接,看看您可以做些什么来改进它的使用?
-
使用异常过滤器并在那里设置你的重定向逻辑。您还可以将基于条件的重定向放在过滤器中。
-
给我更多的信息来帮助你做出适当的回答。
标签: c# asp.net-mvc visual-studio asp.net-web-api2 webapi2