由于处于故障状态而导致通信错误

德鲁维尔

会员
已加入
2020年12月19日
留言内容
12
编程经验
3-5
从Power Automate运行C#包装程序时,出现此错误。但是此错误仅在某些时候返回。重新提交我的电源自动化流程后,代码将按要求工作。

C#:
{
  "Message": "An error has occurred.\r\nclientRequestId: 66b3b4af-edc0-4bbb-b6e2-11e217c00480",
  "ExceptionMessage": "The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication because it is in the Faulted state.",
  "ExceptionType": "System.ServiceModel.CommunicationObjectFaultedException",
  "StackTrace": "\r\nServer stack trace: \r\n   at System.ServiceModel.Channels.CommunicationObject.Close(TimeSpan timeout)\r\n\r\nException rethrown at [0]: \r\n   at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)\r\n   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)\r\n   at System.ServiceModel.ICommunicationObject.Close(TimeSpan timeout)\r\n   at System.ServiceModel.ClientBase`1.System.ServiceModel.ICommunicationObject.Close(TimeSpan timeout)\r\n   at SXA_FlowIntegrationWebAPI.Controllers.MainController.CallMethod(ClassMethodCallRequest request)\r\n   at lambda_method(Closure , Object , Object[] )\r\n   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)\r\n   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Filters.AuthorizationFilterAttribute.<ExecuteAuthorizationFilterAsyncCore>d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()"
}

此临时错误有时会干扰较长的流程,因此必须重新提交。
我的C#控制器代码是:

//It dynamically sets the AIF Url and calls the method to consume AIF services using SXA_FlowIntegrationWebAPI.Helpers; using SXA_FlowIntegrationWebAPI.Models; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace SXA_FlowIntegrationWebAPI.Controllers { public class MainController : ApiController { [ActionName("Method")] [HttpPost] [Authorize] public IHttpActionResult CallMethod(ClassMethodCallRequest request) { dynamic retValue; using (var client = new AX2012.SXAFlowIntegrationServiceClient()) { try { var callContext = new AX2012.CallContext(); callContext.Company = request.companyId; callContext.LogonAsUser = User.Identity.Name; client.InnerChannel.OperationTimeout = new TimeSpan(0,10,00); client.Endpoint.Address = new System.ServiceModel.EndpointAddress(request.aifURL); if (request.methodName == "async") { retValue = ""; //client.callMethodAsync(callContext, request.className, request.methodName, request.dataJsonStr); CallMethodAsyncCustom(client, callContext, request); } else { retValue = client.callMethod(callContext, request.className, request.methodName, request.dataJsonStr); } } catch(Exception e) { return Json(new ClassMethodCallResponse { status = "Error", userName = User.Identity.Name, className = request.className, methodName = request.methodName, aifURL = request.aifURL, error = e }); } } return Json(new ClassMethodCallResponse { status = "Success", userName = User.Identity.Name, className = request.className, methodName = request.methodName, aifURL = request.aifURL, data = retValue, }); } public static async System.Threading.Tasks.Task CallMethodAsyncCustom(AX2012.SXAFlowIntegrationServiceClient client, AX2012.CallContext callContext, ClassMethodCallRequest request) { await System.Threading.Tasks.Task.Run(() => client.callMethodAsync(callContext, request.className, request.methodName, request.dataJsonStr)); return "Completed"; } }:
//It dynamically sets the AIF Url and calls the method to consume AIF services
using SXA_FlowIntegrationWebAPI.Helpers;
using SXA_FlowIntegrationWebAPI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace SXA_FlowIntegrationWebAPI.Controllers
{
public class MainController : ApiController
{
    [ActionName("Method")]
    [HttpPost]
    [Authorize]
    public IHttpActionResult CallMethod(ClassMethodCallRequest request)
    {
        dynamic retValue;
        using (var client = new AX2012.SXAFlowIntegrationServiceClient())
        {
            try
            {
                var callContext = new AX2012.CallContext();
                callContext.Company = request.companyId;
                callContext.LogonAsUser = User.Identity.Name;

                client.InnerChannel.OperationTimeout = new TimeSpan(0,10,00);
                client.Endpoint.Address = new System.ServiceModel.EndpointAddress(request.aifURL);
                if (request.methodName == "async")
                {
                    retValue = "";
                    //client.callMethodAsync(callContext, request.className, request.methodName, request.dataJsonStr);
                    CallMethodAsyncCustom(client, callContext, request);
                }
                else
                {
                    retValue = client.callMethod(callContext, request.className, request.methodName, request.dataJsonStr);
                }
            }
            catch(Exception e)
            {
                return Json(new ClassMethodCallResponse
                {
                    status = "Error",
                    userName = User.Identity.Name,
                    className = request.className,
                    methodName = request.methodName,
                    aifURL = request.aifURL,
                    error = e
                });
            }
        }
        return Json(new ClassMethodCallResponse
        {
            status = "Success",
            userName = User.Identity.Name,
            className = request.className,
            methodName = request.methodName,
            aifURL = request.aifURL,
            data = retValue,
        });
    }

    public static async System.Threading.Tasks.Task<string> CallMethodAsyncCustom(AX2012.SXAFlowIntegrationServiceClient client, AX2012.CallContext callContext, ClassMethodCallRequest request)
    {
         await  System.Threading.Tasks.Task.Run(() => client.callMethodAsync(callContext, request.className, request.methodName, request.dataJsonStr));
         return "Completed";
    }
}

我的猜测是,在添加以下行后,此错误已开始弹出: client.InnerChannel.OperationTimeout = new TimeSpan(0,10,00);
由于请求在1分钟内过期,因此必须添加此行。

您能告诉我为什么有时会出现该通信错误吗?
 

跳伞

工作人员
已加入
2019年4月6日
留言内容
2,497
地点
弗吉尼亚州切萨皮克
编程经验
10+
您是否仅在调用异步时收到错误,还是无论调用同步还是异步都发生错误?
 

德鲁维尔

会员
已加入
2020年12月19日
留言内容
12
编程经验
3-5
无论异步还是调用同步,都会发生这种情况。在我添加1.超时和2.异步之前,这没有发生

另外,即使在同步的情况下,此错误也不会捕获到我的异常块中
 
由主持人最后编辑:

德鲁维尔

会员
已加入
2020年12月19日
留言内容
12
编程经验
3-5
我为此尝试了client.Open和client.close并删除了我的异步方法。但是现在我收到此错误。它也是临时的,仅发生第一次。当我重新提交电源自动化流程时,该错误已解决。是因为超时吗?此错误每隔一段时间第一次出现。

JSON:
{
  "className": "xxx",
  "methodName": "xxx",
  "status": "Error",
  "userName": "xxx",
  "aifURL": "xxx",
  "data": null,
  "error": {
    "ClassName": "System.ServiceModel.CommunicationException",
    "Message": "The socket connection was aborted. This could be caused by an error processing your message or a receive timeout being exceeded by the remote host, or an underlying network resource issue. Local socket timeout was '00:09:59.9843888'.",
    "Data": {},
    "InnerException": {
      "ClassName": "System.IO.IOException",
      "Message": "The read operation failed, see inner exception.",
      "Data": {},
      "InnerException": {
        "ClassName": "System.ServiceModel.CommunicationException",
        "Message": "The socket connection was aborted. This could be caused by an error processing your message or a receive timeout being exceeded by the remote host, or an underlying network resource issue. Local socket timeout was '00:09:59.9843888'.",
        "Data": {},
        "InnerException": {
          "NativeErrorCode": 10054,
          "ClassName": "System.Net.Sockets.SocketException",
          "Message": "An existing connection was forcibly closed by the remote host",
          "Data": {},
          "InnerException": null,
          "HelpURL": null,
          "StackTraceString": "   at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)\r\n   at System.ServiceModel.Channels.SocketConnection.ReadCore(Byte[] buffer, Int32 offset, Int32 size, TimeSpan timeout, Boolean closing)",
          "RemoteStackTraceString": null,
          "RemoteStackIndex": 0,
          "ExceptionMethod": "8\nReceive\nSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\nSystem.Net.Sockets.Socket\nInt32 Receive(Byte[], Int32, Int32, System.Net.Sockets.SocketFlags)",
          "HResult": -2147467259,
          "Source": "System",
          "WatsonBuckets": null
        },
        "HelpURL": null,
        "StackTraceString": "   at System.ServiceModel.Channels.SocketConnection.ReadCore(Byte[] buffer, Int32 offset, Int32 size, TimeSpan timeout, Boolean closing)\r\n   at System.ServiceModel.Channels.SocketConnection.Read(Byte[] buffer, Int32 offset, Int32 size, TimeSpan timeout)\r\n   at System.ServiceModel.Channels.ConnectionStream.Read(Byte[] buffer, Int32 offset, Int32 count)\r\n   at System.Net.FixedSizeReader.ReadPacket(Byte[] buffer, Int32 offset, Int32 count)\r\n   at System.Net.Security.NegotiateStream.StartFrameHeader(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)\r\n   at System.Net.Security.NegotiateStream.StartReading(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)\r\n   at System.Net.Security.NegotiateStream.ProcessRead(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)",
        "RemoteStackTraceString": null,
        "RemoteStackIndex": 0,
        "ExceptionMethod": "8\nReadCore\nSystem.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\nSystem.ServiceModel.Channels.SocketConnection\nInt32 ReadCore(Byte[], Int32, Int32, System.TimeSpan, Boolean)",
        "HResult": -2146233087,
        "Source": "System.ServiceModel",
        "WatsonBuckets": null
      },
      "HelpURL": null,
      "StackTraceString": "   at System.Net.Security.NegotiateStream.ProcessRead(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)\r\n   at System.Net.Security.NegotiateStream.Read(Byte[] buffer, Int32 offset, Int32 count)\r\n   at System.ServiceModel.Channels.StreamConnection.Read(Byte[] buffer, Int32 offset, Int32 size, TimeSpan timeout)",
      "RemoteStackTraceString": null,
      "RemoteStackIndex": 0,
      "ExceptionMethod": "8\nProcessRead\nSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\nSystem.Net.Security.NegotiateStream\nInt32 ProcessRead(Byte[], Int32, Int32, System.Net.AsyncProtocolRequest)",
      "HResult": -2146232800,
      "Source": "System",
      "WatsonBuckets": null
    },
    "HelpURL": null,
    "StackTraceString": "   at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)\r\n   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)\r\n   at SXA_FlowIntegrationWebAPI.AX2012.SXAFlowIntegrationService.callMethod(SXAFlowIntegrationServiceCallMethodRequest request)\r\n   at SXA_FlowIntegrationWebAPI.AX2012.SXAFlowIntegrationServiceClient.callMethod(CallContext CallContext, String _className, String _methodName, String _data)\r\n   at SXA_FlowIntegrationWebAPI.Controllers.MainController.CallMethod(ClassMethodCallRequest request)",
    "RemoteStackTraceString": "\r\nServer stack trace: \r\n   at System.ServiceModel.Channels.StreamConnection.Read(Byte[] buffer, Int32 offset, Int32 size, TimeSpan timeout)\r\n   at System.ServiceModel.Channels.ClientFramingDuplexSessionChannel.SendPreamble(IConnection connection, ArraySegment`1 preamble, TimeoutHelper& timeoutHelper)\r\n   at System.ServiceModel.Channels.ClientFramingDuplexSessionChannel.DuplexConnectionPoolHelper.AcceptPooledConnection(IConnection connection, TimeoutHelper& timeoutHelper)\r\n   at System.ServiceModel.Channels.ConnectionPoolHelper.EstablishConnection(TimeSpan timeout)\r\n   at System.ServiceModel.Channels.ClientFramingDuplexSessionChannel.OnOpen(TimeSpan timeout)\r\n   at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)\r\n   at System.ServiceModel.Channels.ServiceChannel.OnOpen(TimeSpan timeout)\r\n   at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)\r\n   at System.ServiceModel.Channels.ServiceChannel.CallOnceManager.CallOnce(TimeSpan timeout, CallOnceManager cascade)\r\n   at System.ServiceModel.Channels.ServiceChannel.EnsureOpened(TimeSpan timeout)\r\n   at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)\r\n   at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)\r\n   at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)\r\n\r\nException rethrown at [0]: \r\n",
    "RemoteStackIndex": 1,
    "ExceptionMethod": "8\nHandleReturnMessage\nmscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\nSystem.Runtime.Remoting.Proxies.RealProxy\nVoid HandleReturnMessage(System.Runtime.Remoting.Messaging.IMessage, System.Runtime.Remoting.Messaging.IMessage)",
    "HResult": -2146233087,
    "Source": "mscorlib",
    "WatsonBuckets": null
  }
}
 

跳伞

工作人员
已加入
2019年4月6日
留言内容
2,497
地点
弗吉尼亚州切萨皮克
编程经验
10+
是因为超时吗?
是。阅读错误消息(我为您自动换行,因为显然您没有滚动到足够远的右边):
C#:
"Message": "The socket connection was aborted.
This could be caused by an error processing your message
or a receive timeout being exceeded by the remote host,
or an underlying network resource issue.
Local socket timeout was '00:09:59.9843888'.",

我为此尝试了client.Open和client.close并删除了我的异步方法。
向我们显示您的新代码。
 

德鲁维尔

会员
已加入
2020年12月19日
留言内容
12
编程经验
3-5
这是新代码
C#:
public class MainController : ApiController
    {
        [ActionName("Method")]
        [HttpPost]
        [Authorize]
        public IHttpActionResult CallMethod(ClassMethodCallRequest request)
        {
            dynamic retValue;
            bool success = false;
            AX2012.SXAFlowIntegrationServiceClient client = null;       

            try
            {
                client = new AX2012.SXAFlowIntegrationServiceClient();

                var callContext = new AX2012.CallContext();
                callContext.Company = request.companyId;
                callContext.LogonAsUser = User.Identity.Name;

                client.InnerChannel.OperationTimeout = new TimeSpan(0,10,00);
                client.Endpoint.Address = new System.ServiceModel.EndpointAddress(request.aifURL);

                retValue = client.callMethod(callContext, request.className, request.methodName, request.dataJsonStr);
                client.Close();
                success = true;

            }
            catch (Exception e)
            {
                return Json(new ClassMethodCallResponse
                {
                    status = "Error",
                    userName = User.Identity.Name,
                    className = request.className,
                    methodName = request.methodName,
                    aifURL = request.aifURL,
                    error = e
                });
            }
            finally
            {
                if (!success)
                {
                    client.Abort();
                }
            }
            
            return Json(new ClassMethodCallResponse
            {
                status = "Success",
                userName = User.Identity.Name,
                className = request.className,
                methodName = request.methodName,
                aifURL = request.aifURL,
                data = retValue,
            });
        }

    }
 
最佳 底部