You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET MVC5生产环境数据库传输层Error19错误排查求助

ASP.NET MVC5生产环境间歇性数据库连接异常排查求助

仅生产环境会触发以下错误,本地开发环境(localhost)无问题:

A transport-level error has occurred when sending the request to the server. (provider: Session Provider, error: 19 - Physical connection is not usable)

该错误发生在执行CadastrarOcorrenciaSolicitacao和CadastrarAnexos存储过程时,CadastrarOcorrenciaSolicitacao也偶发失败。

相关出错代码(控制器)

[HttpPost]
[ValidateInput(false)]
public JsonResult CadastraOcorrencia(FormCollection formValues, HttpPostedFileBase[] file, bool[] n, string inp_datini = "", string inp_datfim = "")
{
    if (!User.Identity.IsAuthenticated)
        return null;

    object objJson;
    JsonMessage response = new JsonMessage();

    if (!Request.IsAjaxRequest())
    {
        objJson = new
        {
            isValid = false,
            Msg = "Operação Cancelada! Erro 001.1 - Erro ao Cadastrar Ocorrência"
        };

        return Json(objJson, JsonRequestBehavior.AllowGet);
    }

    response.Msg = "";

    int codigo = int.Parse(formValues["sesCOD"]);
    var tituloOcorrencia = formValues["Item3.Titulo"];
    var TextoOcorrencia = formValues["Item3.TextoOcorrencia"];
    int statusOcorrencia = int.Parse(formValues["Item3.StatusCodigo"] as string);
    int tipoOcorrencia = int.Parse(formValues["Item3.TipoOcorrenciaCodigo"] as string);
    string posicaoCliente = "True";
    int itemOcorrencia = int.Parse(formValues["Item3.OcorrenciaItem"] as string);

    int prioridade = 0;
    int.TryParse(formValues["Item3.Prioridade"] as string, out prioridade);

    string dataPRVFechamento = formValues["Item3.DataPrevisaoFechamentoFMT"];
    DateTime? dataHoraPrvFechamento = string.IsNullOrEmpty(dataPRVFechamento)? (DateTime?)null : DateTime.ParseExact(dataPRVFechamento, "dd/MM/yyyy HH:mm", null);

    DateTime? dat_ini = null;
    DateTime? dat_fim = null;

    DateTime dat_ini_ = new DateTime();
    DateTime dat_fim_ = new DateTime();

    if (!string.IsNullOrWhiteSpace(inp_datini))
    {
        bool res = DateTime.TryParse(inp_datini, out dat_ini_);
        if (res)
        {
            dat_ini = dat_ini_;
        }
    }

    if (!string.IsNullOrWhiteSpace(inp_datfim))
    {
        bool resp = DateTime.TryParse(inp_datfim, out dat_fim_);
        if (resp)
        {
            dat_fim = dat_fim_;
        }
    }

    if (TextoOcorrencia.Contains("ó"))
    {
        TextoOcorrencia = TextoOcorrencia.Replace("ó", "ó");
    }
    if (TextoOcorrencia.Contains("Ô"))
    {
        TextoOcorrencia = TextoOcorrencia.Replace("Ô", "Ô");
    }

    string xamlText = HtmlToXamlConverter.ConvertHtmlToXaml(TextoOcorrencia, false);
    RtfConvert rc = new RtfConvert();
    string textRtf = rc.XamlToRtf(xamlText);

    byte[] obyte = Encoding.UTF8.GetBytes(textRtf);
    var OUT_ITEM = new ObjectParameter("OUT_ITEM", typeof(System.Int32));

    switch (posicaoCliente)
    {
        case "True": posicaoCliente = "S"; break;
        case "False": posicaoCliente = "N"; break;
        default: posicaoCliente = "N"; break;
    }

    using (var dbContext = new LazcoInternoEntities())
    {
        try
        {
            dbContext.CadastrarOcorrenciaSolicitacao("MNT", codigo, itemOcorrencia, User.Identity.Name, tituloOcorrencia,
                    statusOcorrencia, tipoOcorrencia, obyte, posicaoCliente, prioridade, dat_ini, dat_fim, dataHoraPrvFechamento, OUT_ITEM);
        }
        catch (Exception exceptionMessage)
        {
            // Log exception here...

            objJson = new
            {
                isValid = false,
                Msg = "Operação Cancelada! Erro 001.3 - Erro ao Cadastrar Ocorrência.",
                Dev = SqlUtils.ExceptionDetails(exceptionMessage)
            };

            return Json(objJson, JsonRequestBehavior.AllowGet);
        }
    }

    byte[] fileData = null;

    using (var dbContext = new LazcoInternoEntities())
    {
        try
        {
            if (itemOcorrencia == 0 && Request.Files.Count > 0)
            {
                for (int i = 0; i < Request.Files.Count; i++)
                {
                    var arq = Request.Files[i];

                    if (arq.ContentLength > 0 && arq.FileName != "")
                    {
                        fileData = new byte[arq.ContentLength];

                        using (var memoryStream = new MemoryStream())
                        {
                            arq.InputStream.CopyTo(memoryStream);
                            fileData = memoryStream.ToArray();
                        }

                        dbContext.CadastrarAnexos("MNT", codigo, 0, arq.FileName, "Arquivo de Solicitação na Web(Ocorrência)", "WEB", fileData, User.Identity.Name, Convert.ToInt32(OUT_ITEM.Value.ToString()));
                    }
                }
            }
        }
        catch (Exception e)
        {
            // Log exception here...

            var objJsonFile = new
            {
                isValid = false,
                Msg = "Operação Cancelada! Erro 001.2 - Ocorreu um Erro ao Salvar o Anexo!",
                Dev = SqlUtils.ExceptionDetails(e)
            };

            return Json(objJsonFile, JsonRequestBehavior.AllowGet);
        }
    }

    objJson = new
    {
        isValid = true,
        Msg = "Ocorrência Cadastrada com Sucesso!"
    };

    return Json(objJson, JsonRequestBehavior.AllowGet);
}

问题详情

  • 仅生产环境调用上述两个存储过程时触发错误,本地无异常;
  • 错误与数据库物理连接相关,疑似连接池、会话或长事务问题。

已尝试方案

  • 使用using语句确保dbContext正确释放;
  • 捕获并记录异常,便于排查根因;
  • 本地环境未观测到异常,但生产环境持续出现该错误。

预期通过CadastrarAnexos存储过程上传文件时能成功保存至数据库,但生产环境执行上传流程时触发上述错误,导致存储过程执行失败、文件上传失败。

错误堆栈信息

"   at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
   at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.Execute(EntityCommand entityCommand, CommandBehavior behavior)
   at System.Data.Entity.Core.EntityClient.EntityCommand.ExecuteReader(CommandBehavior behavior)
   at System.Data.Entity.Core.EntityClient.EntityCommand.ExecuteNonQuery()
   at System.Data.Entity.Core.Objects.ObjectContext.ExecuteFunctionCommand(EntityCommand entityCommand)
   at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
   at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass49.<ExecuteFunction>b__47()
   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
   at System.Data.Entity.Core.Objects.ObjectContext.ExecuteFunction(String functionName, ObjectParameter[] parameters)
   at LazcoInternoDbFirst.Models.LazcoInternoEntities.CadastrarAnexos(String iNP_STATUS, Nullable`1 iNP_CODIGO, Nullable`1 iNP_SEQUEN, String iNP_NOME, String iNP_ANEDES, String iNP_LOCAL, Byte[] iNP_OBJETO, String iNP_USUARI, Nullable`1 iNP_OCOITE)
   at LazcoInternoDbFirst.Controllers.AtendimentoController.CadastraOcorrencia(FormCollection formValues, HttpPostedFileBase[] file, Boolean[] n, String inp_datini, String inp_datfim)"

相关DbContext类代码

namespace LazcoInternoDbFirst.Models
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;
    using System.Data.Entity.Core.Objects;
    using System.Linq;
    
    public partial class LazcoInternoEntities : DbContext
    {
        public LazcoInternoEntities()
            : base("name=LazcoInternoEntities")
        {
        }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }
    
        public virtual DbSet<AspNetRole> AspNetRoles { get; set; }
        public virtual DbSet<AspNetUserClaim> AspNetUserClaims { get; set; }
        public virtual DbSet<AspNetUserLogin> AspNetUserLogins { get; set; }
        public virtual DbSet<AspNetUser> AspNetUsers { get; set; }
        public virtual DbSet<LZ_MINT_USU01> LZ_MINT_USU01 { get; set; }
        
        //all stored procedure function imports "public virtual"

}

恳请有相关经验的人士提供解决方案或排查方向。

内容的提问来源于stack exchange,提问作者Miguel Henrique Pereira

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 22:57:02