gpt4 book ai didi

asp.net - 返回 XmlDocument 的 web 方法中的自定义错误处理

转载 作者:行者123 更新时间:2023-12-02 01:47:28 26 4
gpt4 key购买 nike

我正在与一个具有如下 Web 方法的客户合作:

[WebMethod]
public XmlDocument Send(string stuff)
{
// ...
}

目前有一类异常发生,代码重新抛出,触发ASP.Net标准的异常处理。

我们想更改它,以便 web 方法仍然返回状态代码 500,但我们提供了一些 text/plain 诊断信息,而不是默认的 ASP.Net 内容。

这样做的合适方法是什么?

我已经成功了,使用 Context.Response.End 如下:

[WebMethod]
public XmlDocument Send(string stuff)
{
try
{
// ...normal processing...

return xmlDocument;
}
catch (RelevantException)
{
// ...irrelevant cleanup...

// Send error
Context.Response.StatusCode = 500;
Context.Response.Headers.Add("Content-Type", "text/plain");
Context.Response.Write("...diagnostic information here...");
Context.Response.End();
return null;
}
}

但这感觉很老套,所以我希望有更好的答案。

最佳答案

But that feels hacky, so I'm hoping there's a better answer.

感觉很乱,因为它很乱。

更好的答案是:返回 XML,就像您说的那样,以及您想要包含的任何信息。该服务返回 XML,它旨在供代码使用,而不是供人使用。

[WebMethod]
public XmlDocument Send(string stuff)
{
try
{
// ...normal processing, creates xmlDocument...

return xmlDocument;
}
catch (RelevantException)
{
// ...irrelevant cleanup...

// ...error processing, creates xmlDocument...
Context.Response.StatusCode = 500;
return xmlDocument;
}
}

关于asp.net - 返回 XmlDocument 的 web 方法中的自定义错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24725404/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com