c# – 如何为302状态代码使用handleexeption批注时指定位置
使用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"); } } 编辑: /// <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"; } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |