【问题标题】:WCF Service. How to return HTTP 500 responseWCF 服务。如何返回 HTTP 500 响应
【发布时间】:2013-09-05 16:22:13
【问题描述】:

我有一个访问注册表并返回值的 WCF 服务。我想在某些情况下返回 HTTP 500 响应,例如当我得到从注册表返回的空值时,没有任何异常。这是我的代码。我想返回 HTTP 500 响应,而不是返回“null”字符串。

private string baseKey = "SOFTWARE\\Action\\software\\Station";

public string GetCode()
{
    string Code;
    try
    {
        using (RegistryKey regKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine,
            Environment.Is64BitOperatingSystem ? RegistryView.Registry64 : RegistryView.Registry32))
        {
            using (RegistryKey subKey = regKey.OpenSubKey(baseKey, false))
            {
                Code = (string)subKey.GetValue("Code");
            };
        };

        return string.IsNullOrEmpty(Code) ? "null" : Code;
    }
    catch (Exception ex)
    {
        return "null";
    }
}

如何创建此 HTTP 500 响应以返回给客户端?

请帮忙。

【问题讨论】:

    标签: c# asp.net .net visual-studio-2010 wcf


    【解决方案1】:

    你试过了吗?

    throw new WebFaultException<string>("Registry key not found", HttpStatusCode.InternalServerError);
    

    【讨论】:

      【解决方案2】:

      如果异常冒泡到 WCF,WCF 会将 HTTP 状态设置为 500 并返回错误。

      也就是说,抛出异常以向客户端返回 500 响应。

      【讨论】:

        【解决方案3】:

        你可以注入一个状态码,像这样:

        WebOperationContext ctx = WebOperationContext.Current;
        ctx.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.InternalServerError;
        

        注意:InternalServerError 是映射到 HTTP 500 的 HttpStatusCode 枚举值。

        【讨论】:

        • 非常感谢卡尔。我发现了类似的实现。
        • 太好了,很高兴你找到了你需要的东西。 :-)
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-16
        • 2018-02-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多