2011-02-14 13 views
15

En mi sitio web, deseo que el usuario tenga la capacidad de iniciar/cerrar sesión desde cualquier página. Cuando el usuario seleccione el botón de inicio de sesión, se le presentará un cuadro de diálogo modal para que ingrese sus credenciales.MVC HTML.RenderAction - Error: la duración debe ser un número positivo

Como el inicio de sesión estará en cada página, pensé que crearía una vista parcial para el inicio de sesión y lo agregaría a la página de diseño. Pero cuando lo hice, recibí el siguiente error: Detalles de la excepción: System.InvalidOperationException: la duración debe ser un número positivo.

Hay otras maneras de evitar esto que no usarían vistas parciales, pero creo que esto debería funcionar.

Así que para probar esto, decidí hacer todo lo simple con el siguiente código:

Creado Un diseño de página con el siguiente código

@{Html.RenderAction("_Login", "Account");} 

En el AccountController:

public ActionResult _Login() 
{ 
    return PartialView("_Login"); 
} 

Vista parcial _Login

<a id="signin">Login</a> 

Pero cuando ejecuto esta versión simple, sigo teniendo este error: Detalles de la excepción: System.InvalidOperationException: La duración debe ser un número positivo.

Fuente de puntos de error de "@ {Html.RenderAction (" _ Login " "Cuenta");}"

Hay algunas conversaciones en la web que son similares a mi problema, que lo identifica como error con MVC (ver enlaces a continuación). Pero los enlaces pertenecen a Caching, y no estoy haciendo ningún almacenamiento en caché.

OuputCache caché perfil no funciona para las acciones del niño
http://aspnet.codeplex.com/workitem/7923

Asp.Net MVC 3 parcial de resultados de página Almacenamiento en caché no cumplir Opciones de Configuración de ChildActions Asp.Net MVC 3 Partial Page Output Caching Not Honoring Config Settings

almacenamiento en caché utilizando perfiles de memoria caché no va a funcionar? Caching ChildActions using cache profiles won't work?

No estoy seguro de si esto hace la diferencia, pero lo seguiré agregando aquí. Estoy usando MVC 3 con Razor.


actualización
Seguimiento de la pila

[InvalidOperationException: Duration must be a positive number.] 
    System.Web.Mvc.OutputCacheAttribute.ValidateChildActionConfiguration() +624394 
    System.Web.Mvc.OutputCacheAttribute.OnActionExecuting(ActionExecutingContext filterContext) +127 
    System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +72 
    System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +784922 
    System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +314 
    System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +784976 
    System.Web.Mvc.Controller.ExecuteCore() +159 
    System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +335 
    System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +62 
    System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +20 
    System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +54 
    System.Web.Mvc.<>c__DisplayClass4.<Wrap>b__3() +15 
    System.Web.Mvc.ServerExecuteHttpHandlerWrapper.Wrap(Func`1 func) +41 
    System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride) +1363 

[HttpException (0x80004005): Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper'.] 
    System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride) +2419 
    System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage) +275 
    System.Web.HttpServerUtilityWrapper.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm) +94 
    System.Web.Mvc.Html.ChildActionExtensions.ActionHelper(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues, TextWriter textWriter) +838 
    System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues) +56 
    ASP._Page_Views_Shared_SiteLayout_cshtml.Execute() in c:\Projects\prj Projects\prj\Source\Presentation\prj.PublicWebSite\Views\Shared\SiteLayout.cshtml:80 
    System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +280 
    System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +104 
    System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +173 
    System.Web.WebPages.WebPageBase.Write(HelperResult result) +89 
    System.Web.WebPages.WebPageBase.RenderSurrounding(String partialViewName, Action`1 body) +234 
    System.Web.WebPages.WebPageBase.PopContext() +234 
    System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +384 
    System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() +33 
    System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +784900 
    System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +784900 
    System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +265 
    System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +784976 
    System.Web.Mvc.Controller.ExecuteCore() +159 
    System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +335 
    System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +62 
    System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +20 
    System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +54 
    System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +453 
    System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +371 

Actualizar
cuando rompa en el código, errores en @ {Html.RenderAction ("_ Login", "Cuenta");} con la siguiente excepción.La excepción interna

Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper'. 

at System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride) 
    at System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage) 
    at System.Web.HttpServerUtilityWrapper.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm) 
    at System.Web.Mvc.Html.ChildActionExtensions.ActionHelper(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues, TextWriter textWriter) 
    at System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues) 
    at ASP._Page_Views_Shared_SiteLayout_cshtml.Execute() in c:\Projects\prj Projects\prj\Source\Presentation\prj.PublicWebSite\Views\Shared\SiteLayout.cshtml:line 80 
    at System.Web.WebPages.WebPageBase.ExecutePageHierarchy() 
    at System.Web.Mvc.WebViewPage.ExecutePageHierarchy() 
    at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) 
    at System.Web.WebPages.WebPageBase.Write(HelperResult result) 
    at System.Web.WebPages.WebPageBase.RenderSurrounding(String partialViewName, Action`1 body) 
    at System.Web.WebPages.WebPageBase.PopContext() 
    at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) 
    at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() 
    at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) 

enter image description here


respuesta Gracias Darin Dimitrov

Volver a encontrar, mi AccountController tenía el siguiente atributo

[System.Web.Mvc.OutputCache(NoStore =true, Duration = 0, VaryByParam = "*")].

no creo esto debería causar un problema, pero cuando Eliminé el atributo, todo funcionó.

BarDev

+1

Hmm, eso es raro. Al leer su pregunta, estoy listo para apostar 5 dólares que tiene el almacenamiento en caché habilitado de alguna manera. Intente cambiar el nombre de la acción, controlador. Asegúrese de que la acción a la que llama no esté decorada con el atributo '[OutputCache]'. Intente hacer esto en un nuevo proyecto que empiece desde cero. Estoy seguro de que podrás reducirlo. –

+1

¿Cuál es el seguimiento de la pila? – SLaks

+0

@BarDev, en su stacktrace de excepción podemos ver 'OutputCacheAttribute'. Entonces me tienes 5 dólares :-) –

Respuesta

17

Adición de mi comentario como respuesta:

Hmm, eso es raro. Al leer su pregunta, estoy listo para apostar 5 dólares que tiene el almacenamiento en caché habilitado de alguna manera. Intente cambiar el nombre de la acción, controlador. Asegúrese de que la acción a la que llama no esté decorada con el atributo [OutputCache]. Intente hacer esto en un nuevo proyecto que empiece desde cero. Estoy seguro de que podrás reducirlo.

+0

Estoy teniendo el mismo problema, '[OutputCache (Duration = 0, NoStore = true, VaryByParam =" * ")]' se aplica tanto en el controlador base como en la acción, incluso reinicié mi pc pero sigo teniendo este error, ¿alguna pista? – bjan

+7

Entendido, cualquier atributo que no sea 'Durantion' y' VaryByParam' no están permitidos + 'Duration' debe ser> 0 y' VaryByParam' no debe estar vacío. Consulte [aquí] (http://www.dotnetcurry.com/ShowArticle.aspx?ID=665). ¿Fuiste a este artículo de los comentarios de @frennky en [Caching ChildActions usando los perfiles de caché no funcionará?] (Http://stackoverflow.com/questions/4728958/caching-childactions-using-cache-profiles-wunt-work) – bjan

+0

También verifique su clase de filtro global, 'FilterConfig.cs', para el objeto' OutputCacheAttribute'. Ejemplo: 'filters.Add (nuevo OutputCacheAttribute {VaryByParam =" * ", Duration = 1});' –

1

En algunos casos, puede ser apropiado simplemente crear un segundo método de acción, con el almacenamiento en caché deshabilitado que es llamado por su acción principal.

/// Use this for normal HTTP requests which need to be cached 
    [OutputCache(CacheProfile = "Script")] 
    public ContentResult Foo(string id) 
    { 
     return _Foo(id); 
    } 

    /// Use this for Html.Action 
    public ContentResult _Foo(string id) 
    { 
     return View(); 
    } 

Cuando necesite Html.Action que acaba de llamar _foo en lugar de Foo.

@Html.Action("_Foo", "Bar").ToString(); 

A continuación, puede confiar en la página principal para hacer el almacenamiento en caché.


Otra forma es simplemente pasar por alto todo el asunto 'CacheProfile' para ActionMethod y utilizar my 'DonutCacheAttribute' lugar.

El 'CacheProfile' para ActionMethods actualmente sólo respeta las propiedades Duration y varyByParam - y este método hace que sea fácil de configurar diferentes duraciones de almacenamiento en caché de depuración vs despliegue (asumiendo que usted está usando transformaciones XDT).

2

llegué solucionar el problema mediante la creación de un atributo personalizado OutputCache, que carga manualmente el Duration, VarByCustom y VarByParam del perfil:

public class ChildActionOutputCacheAttribute : OutputCacheAttribute 
{ 
    public ChildActionOutputCacheAttribute(string cacheProfile) 
    { 
     var settings = (OutputCacheSettingsSection)WebConfigurationManager.GetSection("system.web/caching/outputCacheSettings"); 
     var profile = settings.OutputCacheProfiles[cacheProfile]; 
     Duration = profile.Duration; 
     VaryByParam = profile.VaryByParam; 
     VaryByCustom = profile.VaryByCustom; 
    } 
} 

La ventaja de este enfoque es que se llega a seguir manteniendo toda su perfiles en un solo lugar en la web.config.

Esto también se puede encontrar en la pregunta relacionada: https://stackoverflow.com/a/13866280/1373170

Cuestiones relacionadas