如何在ASP.NET页面\错误处理程序中获取没有字符串名称(例如GetType().FullName)比较的异常类型?

如何在ASP.NET页面\错误处理程序中获取没有字符串名称(例如GetType().FullName)比较的异常类型?,.net,asp.net,exception,type-conversion,page-lifecycle,.net,Asp.net,Exception,Type Conversion,Page Lifecycle,有没有比检查异常字符串更好的方法 我更希望在页面上处理这个“捕获所有”错误,但对于SOAP异常(web服务调用),我需要记录服务器上发生的实际异常的详细信息,而不是客户端 “.Detail.InnerText”属性不在泛型异常中,只能在将泛型异常强制转换为SOAP异常后才能获取 protected void Page_Error(object sender, EventArgs e) { Exception ex = Context.Server.GetLastE

有没有比检查异常字符串更好的方法

我更希望在页面上处理这个“捕获所有”错误,但对于SOAP异常(web服务调用),我需要记录服务器上发生的实际异常的详细信息,而不是客户端

“.Detail.InnerText”属性不在泛型异常中,只能在将泛型异常强制转换为SOAP异常后才能获取

    protected void Page_Error(object sender, EventArgs e)
    {
        Exception ex = Context.Server.GetLastError();

        if (ex.GetType().FullName == "System.Web.Services.Protocols.SoapException")
        {
            System.Web.Services.Protocols.SoapException realException = (System.Web.Services.Protocols.SoapException)ex;
            Response.Clear();

            Response.Output.Write(@"<div style='color:maroon; border:solid 1px maroon;'><pre>{0}</pre></div>", realException.Detail.InnerText);
            Response.Output.Write("<div style='color:maroon; border:solid 1px maroon;'><pre>{0}\n{1}</pre></div>", ex.Message, ex.StackTrace);

            Context.ClearError();
            Response.End();
        }
    }
受保护的无效页面\u错误(对象发送方,事件参数e)
{
异常ex=Context.Server.GetLastError();
if(例如GetType().FullName==“System.Web.Services.Protocols.SoapException”)
{
System.Web.Services.Protocols.SoapException realeexception=(System.Web.Services.Protocols.SoapException)ex;
Response.Clear();
Response.Output.Write(@“{0}”,realeException.Detail.InnerText);
Response.Output.Write(“{0}\n{1}”,例如Message,例如StackTrace);
Context.ClearError();
Response.End();
}
}
我认为有一种方法可以在不使用字符串比较的情况下获取底层异常的类型


提前谢谢。

你能试试这样的想法吗:

var ex = Context.Server.GetLastError();

var soapEx = ex as SoapException;
if(soapEx != null)
{
    //Handle SoapException
}
var ex = Context.Server.GetLastError();
if (ex.GetType() == typeof(SoapException) {
  ..
}

你能试试这样的想法吗:

var ex = Context.Server.GetLastError();
if (ex.GetType() == typeof(SoapException) {
  ..
}

使用
as
操作符:

(见附件。)

或比较类型对象:


假设您希望访问
SoapException
的某个成员,则
as
方法可避免多次类型检查。

使用
as
操作符:

(见附件。)

或比较类型对象:


假设您想访问
SoapException
的某个成员,
as
方法避免了多次类型检查。

使用
as
操作符稍微好一点,因此只需要@Dima中的一个cast操作符。这是非常正确的-这确实减少了一个cast操作码,尽管节省的空间并没有那么明显。IIRC,为“as”类型转换发出的指令比C类型转换要贵很多。也许“是”做了同样的事情。无论如何,出于可读性考虑,我倾向于选择我的版本。使用
作为
操作符稍微好一点,这样就只需要一个cast操作符,就像@Dima的一样。非常正确-这确实减少了一个cast操作码,尽管节省的成本并没有那么明显。IIRC,为“as”类型转换发出的指令比C类型转换要贵很多。也许“是”做了同样的事情。无论如何,出于可读性的考虑,我倾向于选择我的版本。
var ex = Context.Server.GetLastError();
if (ex.GetType() == typeof(SoapException) {
  ..
}