首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >mvc 5中带有参数的拦截动作控制器,支持轻量级拦截

mvc 5中带有参数的拦截动作控制器,支持轻量级拦截
EN

Stack Overflow用户
提问于 2018-05-20 22:13:05
回答 1查看 261关注 0票数 0

我不能用参数截取控制器的动作。我正在使用带有LightInject和LightInject.Interception的Asp.Net MVC5。我收到以下错误:

无法将'System.Object[]‘类型的对象强制转换为'System.Web.Mvc.CustomModelBinderAttribute[]'.类型说明:当前web请求执行过程中发生未处理异常。请查看堆栈跟踪,以了解有关错误的更多信息以及错误在代码中的来源。

异常详细信息: System.InvalidCastException:无法将'System.Object[]‘类型的对象强制转换为'System.Web.Mvc.CustomModelBinderAttribute[]'.类型

源错误:

在执行当前web请求期间生成了未处理的异常。可以使用下面的异常堆栈跟踪来识别有关异常的来源和位置的信息。

Stack Trace: 


[InvalidCastException: Unable to cast object of type 'System.Object[]' to type 'System.Web.Mvc.CustomModelBinderAttribute[]'.]
   System.Web.Mvc.ModelBinders.GetBinderFromAttributes(ICustomAttributeProvider element, Action`1 errorAction) +42
   System.Web.Mvc.ReflectedParameterBindingInfo.get_Binder() +102
   System.Web.Mvc.ControllerActionInvoker.GetModelBinder(ParameterDescriptor parameterDescriptor) +28
   System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +38
   System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +105
   System.Web.Mvc.Async.<>c__DisplayClass3_1.<BeginInvokeAction>b__0(AsyncCallback asyncCallback, Object asyncState) +640
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +14
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
   System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +346
   System.Web.Mvc.<>c.<BeginExecuteCore>b__152_0(AsyncCallback asyncCallback, Object asyncState, ExecuteCoreState innerState) +27
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +30
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
   System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +494
   System.Web.Mvc.<>c.<BeginExecute>b__151_1(AsyncCallback asyncCallback, Object callbackState, Controller controller) +16
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +20
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
   System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +403
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +16
   System.Web.Mvc.<>c.<BeginProcessRequest>b__20_0(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState) +54
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +30
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +427
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +48
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +103
   System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +48
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +159

我的代码是(我不插入视图,因为它们没有意义):

// Global.asax
namespace TestMVCInjection
{
    using System;
    using System.Diagnostics;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Routing;
    using LightInject;
    using LightInject.Interception;

    using TestMVCInjection.Controllers;

    public class MvcApplication : HttpApplication
    {
        public void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            //FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            GlobalFilters.Filters.Add(new HandleErrorAttribute());
            //RouteConfig.RegisterRoutes(RouteTable.Routes);
            RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            RouteTable.Routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );

            RegisterLightInject();
        }

        private void RegisterLightInject()
        {
            var container = new ServiceContainer();
            container.RegisterControllers();
            container.EnableMvc();
            container.Intercept((ServiceRegistration c) => c.ServiceType == typeof(HomeController), (IServiceFactory c) => (IInterceptor)new DebugInterceptor());
        }
    }

    public class DebugInterceptor : IInterceptor
    {
        public object Invoke(IInvocationInfo invocationInfo)
        {
            object returnValue = null;
            // Verifico se devo intercettare il metodo
            var mi = invocationInfo.Method;
            var sw = Stopwatch.StartNew();
            string timestamp = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss.fff \"GMT\"zzz");
            string method = $"{invocationInfo.Method.DeclaringType.Name}.{invocationInfo.Method.Name}";
            try
            {
                var parNames = invocationInfo.Method.GetParameters().Select(d => $"{d.Name}: {d.ParameterType}").ToList();
                var parValues = invocationInfo.Arguments.Select(c => $"{c}").ToList();
                string parameters = string.Join(Environment.NewLine, parNames.Select((n, i) => $"{parNames[i]} = {parValues[i]}"));
                string message = $"{nameof(timestamp).ToUpper()}={timestamp}{Environment.NewLine}{nameof(method).ToUpper()}={method}{Environment.NewLine}{nameof(parameters).ToUpper()}{Environment.NewLine}{parameters}";
                Debug.WriteLine(message);
                returnValue = invocationInfo.Proceed();
                message = $"TOOK {nameof(sw.ElapsedMilliseconds)} = {sw.ElapsedMilliseconds} for returning {returnValue} for method {method}";
                Debug.WriteLine(message);
                return returnValue;
            }
            catch (Exception)
            {
                string message = $"Took {nameof(sw.ElapsedMilliseconds)} = {sw.ElapsedMilliseconds} for throwing an exception method {method}";
                Debug.WriteLine(message);
                throw;
            }
        }
    }
}

我的控制器是:

namespace TestMVCInjection.Controllers
{
    using System.Diagnostics;
    using System.Web.Mvc;

    public class HomeController : Controller
    {
        public virtual ActionResult Index(string id)
        {
            Debug.WriteLine("-----> INDEX START <-----");
            var response = View((object)id);
            Debug.WriteLine("-----> INDEX END <-----");
            return response;
        }
    }
}

希望有人能给我指引正确的方向。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-06 04:09:44

在github存储库上发布了一个问题。它已经在几个小时前进行了更正(LightInject.Inteception 2.0.1)。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50435695

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档