
[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"); }} 编辑:
对不起,我有点急忙问这个问题.上面的类使用HandleExceptionAttribute类,该类继承自ExceptionFilterattribute.当我试图调试他们的单元测试时,我没有意识到这一点.单元测试中不会出现此问题,但使用需要重定向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 {解决方法 编辑:感谢您更新了问题.虽然我仍然不确定你为什么要在这个WebAPI方法中重定向.希望这个答案可以提供帮助. 我将处理HandleExceptionAttribute中的所有异常逻辑.您甚至可以使用您正在寻找的302代码从那里重定向.你的HandleExceptionAttribute看起来像这样(我已经包含了3种基于异常返回结果的方法):
public sealed class HandleExceptionAttribute : ExceptionFilterattribute{ public overrIDe voID OnException(httpActionExecutedContext context) { //Todo: we can handle all types of exceptions here. Out of memory,divIDe by zero,etc etc. if (context.Exception is InvalIDOperationException) { var httpResponseMessage = context.Request.CreateResponse(httpStatusCode.Redirect); httpResponseMessage.headers.Location = new Uri("http://www.YourRedirectUrl"); throw new httpResponseException(httpResponseMessage); } if (context.Exception is UnauthorizedAccessException) { context.Response = context.Request.CreateErrorResponse(httpStatusCode.Unauthorized,context.Exception.Message); return; } if (context.Exception is TimeoutException) { throw new httpResponseException(context.Request.CreateResponse(httpStatusCode.RequestTimeout,context.Exception.Message)); } context.Response = context.Request.CreateErrorResponse(httpStatusCode.InternalServerError,"Unable to process your request."); }} 但是,如果您真的想按照您的要求完成它,可以在GetHandleException方法中添加第二个参数.这将接收消息字符串(或URL),然后在HandleExceptionAttribute中将重定向url添加到参数(ActionArguements):
public IhttpActionResult GetHandleException(int num,string message = ""){ switch (num) { case 12: return Redirect(message); //message string would be your url default: throw new Exception("base exception"); }} 然后你的HandleExceptionAttribute看起来像这样:
public sealed class HandleExceptionAttribute : ExceptionFilterattribute{ public overrIDe voID OnException(httpActionExecutedContext context) { context.ActionContext.ActionArguments["message"] = "your redirect URL"; }} 总结 以上是内存溢出为你收集整理的c# – 如何为302状态代码使用handleexeption批注时指定位置全部内容,希望文章能够帮你解决c# – 如何为302状态代码使用handleexeption批注时指定位置所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)