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

时间: 2024-10-13 04:50:27

ASPNET MVC如何正确的中断请求?的相关文章

Aspnet MVC 异步调用

一个简图来描述下Aspnet MVC下的异步调用 { request } / \/ -------ISS------- > work thread | | \ route - aysn controller | | \ [invoke] clr thread pool | / | / | / complete -> asyncManager | / |------asyncManager 从简图可以了解: 用户发送请求,服务器路由到控制器,控制器到action,action内部通过线程池调用新

NU1002 The dependency Microsoft.AspNet.Mvc 5.2.3 in project dotnetstarter does not support framework

NU1002 The dependency Microsoft.AspNet.Mvc 5.2.3 in project dotnetstarter does not support framework DNXCore,Version=v5.0. 解决"CS0234 The type or namespace name 'Mvc' does not exist in the namespace 'Microsoft.AspNet' (are you missing an assembly refe

AspNet MVC中各种上下文理解

0  前言 AspNet MVC中比较重要的上下文,有如下: 核心的上下文有HttpContext(请求上下文),ControllerContext(控制器上下文) 过滤器有关有五个的上下文ActionExecutingContext,ActionExecutedContext,ResultExecutingContext,ResultExecutedContext,ExceptionContext 视图相关的上下文ViewContext 这些上下文之间的关系如下图所示 说明: 1.Contro

AspNet MVC : 操作/控制器过滤器(action filter)

1.Action Filter Action Filter提供了在执行action/controller前后对请求/响应修改的能力,可以应用于action和控制器上,作用在控制器上将自动被应用到该控制器下所有的action. 常见的应用场景例如: 用户验证授权, 修改view的返回结果,修改response头,日志记录,异常/错误处理等 . AspNet MVC包含四种类型的action filter: a.Auth Filter 验证过滤器,实现IAuthorizationFilter,用于针

【ASP.Net MVC】AspNet Mvc一些总结

AspNet Mvc一些总结 RestaurantReview.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text.RegularExpressions; using System.Web; using System.Web.M

【ASP.Net MVC】在AspNet Mvc使用Ajax

目录 一.使用System.Web.Mvc.Ajax 1.1 System.Web.Mvc.Ajax.BeginForm 1.2 System.Web.Mvc.Ajax.ActionLink 二.手工打造自己的“非介入式”Javascript” 一.使用System.Web.Mvc.Ajax 1.1 System.Web.Mvc.Ajax.BeginForm 第一步:用Ajax.BeginForm创建Form @using (Ajax.BeginForm( new AjaxOptions() {

Aspnet Mvc 前后端分离项目手记(二)关于token认证

在前后端分离的项目中,首先我们要解决的问题就是身份认证 以往的时候,我们使用cookie+session,或者只用cookie来保持会话. 一,先来复习一下cookie和session 首先我们来复习一下在aspnet中cookie和session的关系,做一个简单试验 这是一个普通的view没有任何处理 可以看到,没有任何东西(cookie),然后当我们写入一个session之后 会发现多了一个名为ASP.NET_SessionId的cookie.我们都知道在aspnet中,session是保

MVC4 AspNet MVC下的Ajax / 使用JQuery做相关的Ajax请求

源码参考:链接:http://pan.baidu.com/s/1pKhHHMj  密码:mkr4 1:新建-->项目-->Web-->ASP.NET MVC 4 Web 应用程序.命名为:Mvc4JQueryAjaxDemo 2:新建控制器:在Controllers文件夹上 右键-->添加-->控制器,命名为:HomeController (HomeController .cs) 3:在控制器HomeController中新增Action: GetDate() 1 using

AspNet Mvc 路由解析中添加.html 等后缀 出现404错误的解决办法

使用Mvc 有时候我们希望,浏览地址以.html .htm 等后缀名进行结尾. 于是我们就在RouteConfig 中修改路由配置信息,修改后的代码如下 routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}.html", defaults: new { controller =