ASPNET MVC如何正确的中断请求?

以前在aspnet中一直是Response.End();

在这之后的当前请求应有的代码都不会执行了,

但是在aspnetmvc中,就算调用Response.End();还是会执行!

如果你在action中的逻辑需要中断,你可以变通的通过逻辑判断来中断,

比如

if(ok)
{
    //应有的逻辑
}
else
{
    //中断            
}

//或者

if(!ok)
    return Content("NO");

 但是如果是在过滤器中

        protected virtual void OnActionExecuted(ActionExecutedContext filterContext);
        protected virtual void OnActionExecuting(ActionExecutingContext filterContext);
        protected virtual void OnAuthorization(AuthorizationContext filterContext);
        protected virtual void OnException(ExceptionContext filterContext);
        protected virtual void OnResultExecuted(ResultExecutedContext filterContext);
        protected virtual void OnResultExecuting(ResultExecutingContext filterContext);

return or Response.End(); 是无效的!

教你正确的aspnetmvc Cancel姿势:

那就是赋值 filterContext.Result!

例如OnActionExecuting

  protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var headerAuth = filterContext.HttpContext.Request.Headers["_applogin_"];
            if (string.IsNullOrEmpty(headerAuth))
            {
                filterContext.Result = new ContentResult()
                {
                    Content = "{code:9999,message:‘no login‘}",
                    ContentEncoding = Encoding.UTF8
                };
            }

            base.OnActionExecuting(filterContext);
        }
    }

 

为什么赋值了Context.Result就不会继续执行action的逻辑呢?

aspnetmvc源码:ControllerActionInvoker.cs

using Microsoft.Web.Infrastructure.DynamicValidationHelper;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Web.Mvc.Properties;
namespace System.Web.Mvc
{
	public class ControllerActionInvoker : IActionInvoker
	{
		private static readonly ControllerDescriptorCache _staticDescriptorCache = new ControllerDescriptorCache();
		private ModelBinderDictionary _binders;
		private Func<ControllerContext, ActionDescriptor, IEnumerable<Filter>> _getFiltersThunk = new Func<ControllerContext, ActionDescriptor, IEnumerable<Filter>>(FilterProviders.Providers.GetFilters);
		private ControllerDescriptorCache _instanceDescriptorCache;
		protected internal ModelBinderDictionary Binders
		{
			get
			{
				if (this._binders == null)
				{
					this._binders = ModelBinders.Binders;
				}
				return this._binders;
			}
			set
			{
				this._binders = value;
			}
		}
		internal ControllerDescriptorCache DescriptorCache
		{
			get
			{
				if (this._instanceDescriptorCache == null)
				{
					this._instanceDescriptorCache = ControllerActionInvoker._staticDescriptorCache;
				}
				return this._instanceDescriptorCache;
			}
			set
			{
				this._instanceDescriptorCache = value;
			}
		}
		public ControllerActionInvoker()
		{
		}
		internal ControllerActionInvoker(params object[] filters) : this()
		{
			if (filters != null)
			{
				this._getFiltersThunk = ((ControllerContext cc, ActionDescriptor ad) => 
					from f in filters
					select new Filter(f, FilterScope.Action, null));
			}
		}
		protected virtual ActionResult CreateActionResult(ControllerContext controllerContext, ActionDescriptor actionDescriptor, object actionReturnValue)
		{
			if (actionReturnValue == null)
			{
				return new EmptyResult();
			}
			ActionResult arg_2B_0;
			if ((arg_2B_0 = (actionReturnValue as ActionResult)) == null)
			{
				arg_2B_0 = new ContentResult
				{
					Content = Convert.ToString(actionReturnValue, CultureInfo.InvariantCulture)
				};
			}
			return arg_2B_0;
		}
		protected virtual ControllerDescriptor GetControllerDescriptor(ControllerContext controllerContext)
		{
			Type controllerType = controllerContext.Controller.GetType();
			return this.DescriptorCache.GetDescriptor(controllerType, () => new ReflectedControllerDescriptor(controllerType));
		}
		protected virtual ActionDescriptor FindAction(ControllerContext controllerContext, ControllerDescriptor controllerDescriptor, string actionName)
		{
			return controllerDescriptor.FindAction(controllerContext, actionName);
		}
		protected virtual FilterInfo GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
		{
			return new FilterInfo(this._getFiltersThunk(controllerContext, actionDescriptor));
		}
		private IModelBinder GetModelBinder(ParameterDescriptor parameterDescriptor)
		{
			return parameterDescriptor.BindingInfo.Binder ?? this.Binders.GetBinder(parameterDescriptor.ParameterType);
		}
		protected virtual object GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor)
		{
			Type parameterType = parameterDescriptor.ParameterType;
			IModelBinder modelBinder = this.GetModelBinder(parameterDescriptor);
			IValueProvider valueProvider = controllerContext.Controller.ValueProvider;
			string modelName = parameterDescriptor.BindingInfo.Prefix ?? parameterDescriptor.ParameterName;
			Predicate<string> propertyFilter = ControllerActionInvoker.GetPropertyFilter(parameterDescriptor);
			ModelBindingContext bindingContext = new ModelBindingContext
			{
				FallbackToEmptyPrefix = parameterDescriptor.BindingInfo.Prefix == null,
				ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, parameterType),
				ModelName = modelName,
				ModelState = controllerContext.Controller.ViewData.ModelState,
				PropertyFilter = propertyFilter,
				ValueProvider = valueProvider
			};
			object obj = modelBinder.BindModel(controllerContext, bindingContext);
			return obj ?? parameterDescriptor.DefaultValue;
		}
		protected virtual IDictionary<string, object> GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
		{
			Dictionary<string, object> dictionary = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
			ParameterDescriptor[] parameters = actionDescriptor.GetParameters();
			ParameterDescriptor[] array = parameters;
			for (int i = 0; i < array.Length; i++)
			{
				ParameterDescriptor parameterDescriptor = array[i];
				dictionary[parameterDescriptor.ParameterName] = this.GetParameterValue(controllerContext, parameterDescriptor);
			}
			return dictionary;
		}
		private static Predicate<string> GetPropertyFilter(ParameterDescriptor parameterDescriptor)
		{
			ParameterBindingInfo bindingInfo = parameterDescriptor.BindingInfo;
			return (string propertyName) => BindAttribute.IsPropertyAllowed(propertyName, bindingInfo.Include.ToArray<string>(), bindingInfo.Exclude.ToArray<string>());
		}
		public virtual bool InvokeAction(ControllerContext controllerContext, string actionName)
		{
			if (controllerContext == null)
			{
				throw new ArgumentNullException("controllerContext");
			}
			if (string.IsNullOrEmpty(actionName))
			{
				throw new ArgumentException(MvcResources.Common_NullOrEmpty, "actionName");
			}
			ControllerDescriptor controllerDescriptor = this.GetControllerDescriptor(controllerContext);
			ActionDescriptor actionDescriptor = this.FindAction(controllerContext, controllerDescriptor, actionName);
			if (actionDescriptor != null)
			{
				FilterInfo filters = this.GetFilters(controllerContext, actionDescriptor);
				try
				{
					AuthorizationContext authorizationContext = this.InvokeAuthorizationFilters(controllerContext, filters.AuthorizationFilters, actionDescriptor);
					if (authorizationContext.Result != null)
					{
						this.InvokeActionResult(controllerContext, authorizationContext.Result);
					}
					else
					{
						if (controllerContext.Controller.ValidateRequest)
						{
							ControllerActionInvoker.ValidateRequest(controllerContext);
						}
						IDictionary<string, object> parameterValues = this.GetParameterValues(controllerContext, actionDescriptor);
						ActionExecutedContext actionExecutedContext = this.InvokeActionMethodWithFilters(controllerContext, filters.ActionFilters, actionDescriptor, parameterValues);
						this.InvokeActionResultWithFilters(controllerContext, filters.ResultFilters, actionExecutedContext.Result);
					}
				}
				catch (ThreadAbortException)
				{
					throw;
				}
				catch (Exception exception)
				{
					ExceptionContext exceptionContext = this.InvokeExceptionFilters(controllerContext, filters.ExceptionFilters, exception);
					if (!exceptionContext.ExceptionHandled)
					{
						throw;
					}
					this.InvokeActionResult(controllerContext, exceptionContext.Result);
				}
				return true;
			}
			return false;
		}
		protected virtual ActionResult InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary<string, object> parameters)
		{
			object actionReturnValue = actionDescriptor.Execute(controllerContext, parameters);
			return this.CreateActionResult(controllerContext, actionDescriptor, actionReturnValue);
		}
		internal static ActionExecutedContext InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func<ActionExecutedContext> continuation)
		{
			filter.OnActionExecuting(preContext);
			if (preContext.Result != null)
			{
				return new ActionExecutedContext(preContext, preContext.ActionDescriptor, true, null)
				{
					Result = preContext.Result
				};
			}
			bool flag = false;
			ActionExecutedContext actionExecutedContext = null;
			try
			{
				actionExecutedContext = continuation();
			}
			catch (ThreadAbortException)
			{
				actionExecutedContext = new ActionExecutedContext(preContext, preContext.ActionDescriptor, false, null);
				filter.OnActionExecuted(actionExecutedContext);
				throw;
			}
			catch (Exception exception)
			{
				flag = true;
				actionExecutedContext = new ActionExecutedContext(preContext, preContext.ActionDescriptor, false, exception);
				filter.OnActionExecuted(actionExecutedContext);
				if (!actionExecutedContext.ExceptionHandled)
				{
					throw;
				}
			}
			if (!flag)
			{
				filter.OnActionExecuted(actionExecutedContext);
			}
			return actionExecutedContext;
		}
		protected virtual ActionExecutedContext InvokeActionMethodWithFilters(ControllerContext controllerContext, IList<IActionFilter> filters, ActionDescriptor actionDescriptor, IDictionary<string, object> parameters)
		{
			ActionExecutingContext preContext = new ActionExecutingContext(controllerContext, actionDescriptor, parameters);
			Func<ActionExecutedContext> seed = () => new ActionExecutedContext(controllerContext, actionDescriptor, false, null)
			{
				Result = this.InvokeActionMethod(controllerContext, actionDescriptor, parameters)
			};
			Func<ActionExecutedContext> func = filters.Reverse<IActionFilter>().Aggregate(seed, (Func<ActionExecutedContext> next, IActionFilter filter) => () => ControllerActionInvoker.InvokeActionMethodFilter(filter, preContext, next));
			return func();
		}
		protected virtual void InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult)
		{
			actionResult.ExecuteResult(controllerContext);
		}
		internal static ResultExecutedContext InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func<ResultExecutedContext> continuation)
		{
			filter.OnResultExecuting(preContext);
			if (preContext.Cancel)
			{
				return new ResultExecutedContext(preContext, preContext.Result, true, null);
			}
			bool flag = false;
			ResultExecutedContext resultExecutedContext = null;
			try
			{
				resultExecutedContext = continuation();
			}
			catch (ThreadAbortException)
			{
				resultExecutedContext = new ResultExecutedContext(preContext, preContext.Result, false, null);
				filter.OnResultExecuted(resultExecutedContext);
				throw;
			}
			catch (Exception exception)
			{
				flag = true;
				resultExecutedContext = new ResultExecutedContext(preContext, preContext.Result, false, exception);
				filter.OnResultExecuted(resultExecutedContext);
				if (!resultExecutedContext.ExceptionHandled)
				{
					throw;
				}
			}
			if (!flag)
			{
				filter.OnResultExecuted(resultExecutedContext);
			}
			return resultExecutedContext;
		}
		protected virtual ResultExecutedContext InvokeActionResultWithFilters(ControllerContext controllerContext, IList<IResultFilter> filters, ActionResult actionResult)
		{
			ResultExecutingContext preContext = new ResultExecutingContext(controllerContext, actionResult);
			Func<ResultExecutedContext> seed = delegate
			{
				this.InvokeActionResult(controllerContext, actionResult);
				return new ResultExecutedContext(controllerContext, actionResult, false, null);
			};
			Func<ResultExecutedContext> func = filters.Reverse<IResultFilter>().Aggregate(seed, (Func<ResultExecutedContext> next, IResultFilter filter) => () => ControllerActionInvoker.InvokeActionResultFilter(filter, preContext, next));
			return func();
		}
		protected virtual AuthorizationContext InvokeAuthorizationFilters(ControllerContext controllerContext, IList<IAuthorizationFilter> filters, ActionDescriptor actionDescriptor)
		{
			AuthorizationContext authorizationContext = new AuthorizationContext(controllerContext, actionDescriptor);
			foreach (IAuthorizationFilter current in filters)
			{
				current.OnAuthorization(authorizationContext);
				if (authorizationContext.Result != null)
				{
					break;
				}
			}
			return authorizationContext;
		}
		protected virtual ExceptionContext InvokeExceptionFilters(ControllerContext controllerContext, IList<IExceptionFilter> filters, Exception exception)
		{
			ExceptionContext exceptionContext = new ExceptionContext(controllerContext, exception);
			foreach (IExceptionFilter current in filters.Reverse<IExceptionFilter>())
			{
				current.OnException(exceptionContext);
			}
			return exceptionContext;
		}
		internal static void ValidateRequest(ControllerContext controllerContext)
		{
			if (controllerContext.IsChildAction)
			{
				return;
			}
			HttpContext current = HttpContext.Current;
			if (current != null)
			{
				ValidationUtility.EnableDynamicValidation(current);
			}
			controllerContext.HttpContext.Request.ValidateInput();
		}
	}
}

  

ContentResult
EmptyResult
FileResult
FileContentResult
FilePathResult
FileStreamResult
HttpUnauthorizedResult
HttpUnauthorizedResult
HttpUnauthorizedResult
JavaScriptResult
JsonResult
RedirectResult
RedirectToRouteResult
ViewResultBase
PartialViewResult
ViewResult

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。