try mvc catch application_error c# .net asp.net-mvc-3 wcf exception-handling

c# - catch - El servicio WCF que devuelve el "servicio solicitado ''...'' no se pudo activar" la primera vez que se accede desde un sitio MVC



application_error mvc (8)

Tenemos un servicio WCF (sin seguridad) al que accede un sitio web de MVC3.

En las máquinas de desarrollo no tenemos problemas, pero cuando nuestra configuración de TeamCity construye la versión central y la implementa en IIS7 la primera vez que cargamos el sitio de MVC3 y accede al servicio de WCF, la llamada de servicio devuelve el mensaje:

System.ServiceModel.ServiceActivationException: el servicio solicitado, ''http: // localhost: 83 / ABCStaticData / StaticDataService.svc'' no se pudo activar. Consulte los registros de seguimiento de diagnóstico del servidor para obtener más información. **

Si golpeamos de inmediato el mismo sitio nuevamente, todo funciona bien.

La pista de la pila del servidor cuando arroja el error es:

Rastro de la pila del servidor:

at System.ServiceModel.Channels.HttpChannelUtilities.ValidateRequestReplyResponse(HttpWebRequest request, HttpWebResponse response, HttpChannelFactory1 factory, WebException responseException, ChannelBinding channelBinding) at System.ServiceModel.Channels.HttpChannelFactory1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout) at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout) at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout) at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation) at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message) Exception rethrown at [0]: at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) at ABC.StaticData.Editor.StaticDataServiceProxy.IStaticDataService.GetAllMarkets() at ABC.StaticData.Editor.StaticDataServiceProxy.StaticDataServiceClient.GetAllMarkets() in c:/BuildAgent/work/55a3bcc468adcccb/StaticData/ABC.StaticData.Editor/Service References/StaticDataServiceProxy/Reference.cs:line 3195 at ABC.StaticData.Editor.Controllers.MarketsController.<>c__DisplayClass22.<.ctor>b__13() in c:/BuildAgent/work/55a3bcc468adcccb/StaticData/ABC.StaticData.Editor/Controllers/MarketsController.cs:line 263 at ABC.StaticData.Editor.Controllers.MarketsController.Index() in c:/BuildAgent/work/55a3bcc468adcccb/StaticData/ABC.StaticData.Editor/Controllers/MarketsController.cs:line 306

¿Alguien tiene alguna idea sobre qué podría estar causando el problema o dónde empezar a buscar?

ACTUALIZACIÓN: me olvidé de mencionar la primera que si no accedemos al sitio por un tiempo y luego volvemos, nos da el mismo error, luego vuelve a funcionar la segunda vez.

ACTUALIZACIÓN2: este es el texto de entrada del registro de eventos:

WebHost failed to process a request. Sender Information: System.ServiceModel.ServiceHostingEnvironment+HostingManager/3043589 Exception: System.ServiceModel.ServiceActivationException: The service ''/ABCStaticData/StaticDataService.svc'' cannot be activated due to an exception during compilation. The exception message is: Could not load type ''System.Runtime.CompilerServices.AsyncStateMachineAttribute'' from assembly ''mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089''.. ---> System.TypeLoadException: Could not load type ''System.Runtime.CompilerServices.AsyncStateMachineAttribute'' from assembly ''mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089''. at System.ModuleHandle.ResolveType(RuntimeModule module, Int32 typeToken, IntPtr* typeInstArgs, Int32 typeInstCount, IntPtr* methodInstArgs, Int32 methodInstCount, ObjectHandleOnStack type) at System.ModuleHandle.ResolveTypeHandleInternal(RuntimeModule module, Int32 typeToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext) at System.Reflection.RuntimeModule.ResolveType(Int32 metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) at System.Reflection.CustomAttribute.FilterCustomAttributeRecord(CustomAttributeRecord caRecord, MetadataImport scope, Assembly& lastAptcaOkAssembly, RuntimeModule decoratedModule, MetadataToken decoratedToken, RuntimeType attributeFilterType, Boolean mustBeInheritable, Object[] attributes, IList derivedAttributes, RuntimeType& attributeType, IRuntimeMethodInfo& ctor, Boolean& ctorHasParameters, Boolean& isVarArg) at System.Reflection.CustomAttribute.IsCustomAttributeDefined(RuntimeModule decoratedModule, Int32 decoratedMetadataToken, RuntimeType attributeFilterType, Boolean mustBeInheritable) at System.Reflection.CustomAttribute.IsDefined(RuntimeMethodInfo method, RuntimeType caType, Boolean inherit) at System.Reflection.RuntimeMethodInfo.IsDefined(Type attributeType, Boolean inherit) at Ninject.Infrastructure.Language.ExtensionsForMemberInfo.HasAttribute(MemberInfo member, Type type) at Ninject.Selection.Heuristics.StandardInjectionHeuristic.ShouldInject(MemberInfo member) at Ninject.Selection.Selector.<>c__DisplayClassa.<SelectMethodsForInjection>b__9(IInjectionHeuristic h) at System.Linq.Enumerable.Any[TSource](IEnumerable`1 source, Func`2 predicate) at Ninject.Selection.Selector.<SelectMethodsForInjection>b__8(MethodInfo m) at System.Linq.Enumerable.WhereArrayIterator`1.MoveNext() at Ninject.Planning.Strategies.MethodReflectionStrategy.Execute(IPlan plan) at Ninject.Planning.Planner.<>c__DisplayClass1.<CreateNewPlan>b__0(IPlanningStrategy s) at Ninject.Infrastructure.Language.ExtensionsForIEnumerableOfT.Map[T](IEnumerable`1 series, Action`1 action) at Ninject.Planning.Planner.CreateNewPlan(Type type) at Ninject.Planning.Planner.GetPlan(Type type) at Ninject.Activation.Providers.StandardProvider.Create(IContext context) at Ninject.Activation.Context.Resolve() at Ninject.KernelBase.<>c__DisplayClass10.<Resolve>b__c(IBinding binding) at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext() at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source) at Ninject.Planning.Targets.Target`1.GetValue(Type service, IContext parent) at Ninject.Planning.Targets.Target`1.ResolveWithin(IContext parent) at Ninject.Activation.Providers.StandardProvider.GetValue(IContext context, ITarget target) at Ninject.Activation.Providers.StandardProvider.<>c__DisplayClass4.<Create>b__2(ITarget target) at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext() at System.Linq.Buffer`1..ctor(IEnumerable`1 source) at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source) at Ninject.Activation.Providers.StandardProvider.Create(IContext context) at Ninject.Activation.Context.Resolve() at Ninject.KernelBase.<>c__DisplayClass10.<Resolve>b__c(IBinding binding) at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext() at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source) at Ninject.Planning.Targets.Target`1.GetValue(Type service, IContext parent) at Ninject.Planning.Targets.Target`1.ResolveWithin(IContext parent) at Ninject.Activation.Providers.StandardProvider.GetValue(IContext context, ITarget target) at Ninject.Activation.Providers.StandardProvider.<>c__DisplayClass4.<Create>b__2(ITarget target) at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext() at System.Linq.Buffer`1..ctor(IEnumerable`1 source) at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source) at Ninject.Activation.Providers.StandardProvider.Create(IContext context) at Ninject.Activation.Context.Resolve() at Ninject.KernelBase.<>c__DisplayClass10.<Resolve>b__c(IBinding binding) at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext() at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source) at Ninject.Extensions.Wcf.BaseNinjectServiceHostFactory.CreateServiceHost(Type serviceType, Uri[] baseAddresses) at System.ServiceModel.Activation.ServiceHostFactory.CreateServiceHost(String constructorString, Uri[] baseAddresses) at System.ServiceModel.ServiceHostingEnvironment.HostingManager.CreateService(String normalizedVirtualPath, EventTraceActivity eventTraceActivity) at System.ServiceModel.ServiceHostingEnvironment.HostingManager.ActivateService(ServiceActivationInfo serviceActivationInfo, EventTraceActivity eventTraceActivity) at System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath, EventTraceActivity eventTraceActivity) --- End of inner exception stack trace --- at System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath, EventTraceActivity eventTraceActivity) at System.ServiceModel.ServiceHostingEnvironment.EnsureServiceAvailableFast(String relativeVirtualPath, EventTraceActivity eventTraceActivity) Process Name: w3wp Process ID: 3248

Solo otro punto que estamos desarrollando usando .NET 4.5 y Visual Studio 2012 RC.


¿La extensión .svc está registrada en IIS?

Ver MSDN para más detalles.


Cada vez que tengo el mismo problema, reinicio mi computadora y funciona bien. Libera memoria


Compruebe que la memoria del servidor en el que está alojando los servicios no está llena.


Este error se produce si instala IIS después de instalar Windows Communication Foundation (WCF). Para solucionarlo, simplemente ejecute el siguiente comando:

"%WINDIR%/Microsoft.Net/Framework/v3.0/Windows Communication Foundation/ServiceModelReg.exe" -r

Fuente: el servicio hospedado de IIS falla


He pulsado el mismo "No se pudo cargar el tipo ''System.Runtime.CompilerServices.AsyncStateMachineAttribute''", lo que descubrí fue porque había creado mi aplicación utilizando VS 2012 RTM, pero luego traté de implementarla en una máquina que solo tenía 4.5 Beta. El AsyncStateMachineAttribute es un nuevo tipo agregado después de Beta.


Me las arreglé para resolver un problema similar de ''System.ServiceModel.ServiceActivationException'' al azar (excepción arrojada, y luego ejecutar el segundo hit). El motivo de la excepción en mi caso fue la falta de memoria en el servidor. Para confirmar el problema de memoria, puede hacer lo siguiente:

Servicio web de solicitud de aplicación:

System.ServiceModel.ServiceActivationException: The requested service, ''XXX'' could not be activated. See the server''s diagnostic trace logs for more information. Server stack trace: at System.ServiceModel.Channels.HttpChannelUtilities.ValidateRequestReplyResponse(HttpWebRequest request, HttpWebResponse response, HttpChannelFactory`1 factory, WebException responseException, ChannelBinding channelBinding) at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout) at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout) at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout) at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation) at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

Registro de seguimiento de WCF: nada registrado.

En el servidor que aloja el servicio wcf (el mismo que el de la aplicación que llama por cierto) en los registros de eventos, a excepción de mucha información basura que he encontrado:

Detalles del evento personalizado:

WebHost failed to process a request. Sender Information: System.ServiceModel.ServiceHostingEnvironment+HostingManager/58366981 Exception: System.ServiceModel.ServiceActivationException: The service ''xxx'' cannot be activated due to an exception during compilation. The exception message is: Memory gates checking failed because the free memory (xxx bytes) is less than 5% of total memory. As a result, the service will not be available for incoming requests. To resolve this, either reduce the load on the machine or adjust the value of minFreeMemoryPercentageToActivateService on the serviceHostingEnvironment config element.. ---> System.InsufficientMemoryException: Memory gates checking failed because the free memory (xxx bytes) is less than 5% of total memory. As a result, the service will not be available for incoming requests. To resolve this, either reduce the load on the machine or adjust the value of minFreeMemoryPercentageToActivateService on the serviceHostingEnvironment config element.

Así que la solución para mí fue: 1. agregar más RAM 2. liberar algunos de RAM (solución temporal) 3. actualizar la configuración web del servicio web:

<configuration> <system.serviceModel> <serviceHostingEnvironment ... minFreeMemoryPercentageToActivateService="0" /> </system.serviceModel> </configuration>


Yo también tuve ese problema, lo que hice fue:

  • Vaya al directorio en el sistema de archivos donde reside el servicio
  • Tendrás 2 archivos para el servicio
    • yourService.svc
    • yourService.svc.cs
  • Abra el archivo yourService.svc y asegúrese de que su servicio esté configurado, y el código detrás se vea así:

    <%@ ServiceHost Language="C#" Debug="true" Service="YourNamespace.yourService.svc" CodeBehind="yourService.svc.cs" %>

Arreglé mi problema de esa manera. ¡Espero que ayude!


Yo también tuve este problema y simplemente lo puse

<serviceHostingEnvironment minFreeMemoryPercentageToActivateService="1">

debajo

<system.serviceModel>

Y todo funciona bien