Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/256.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何自定义WCF错误行为_C#_Wcf - Fatal编程技术网

C# 如何自定义WCF错误行为

C# 如何自定义WCF错误行为,c#,wcf,C#,Wcf,我正在创建一个WCF服务来提供REST-fulWebHTTP服务。这就是我想要的: 这将返回JSON/XML格式的结果 这将返回一条自定义错误消息,而不是标准的“未找到端点”。错误 我阅读了关于IErrorHandler接口和扩展WebHttpBehavior类的内容。但不起作用。最简单的方法是定义处理“未找到”案例的操作-使用“*”的UriTemplate(如果没有其他模板与传入请求匹配,它将匹配)。下面的代码显示了一个示例 public class Post_0424d917_89cd_

我正在创建一个WCF服务来提供REST-fulWebHTTP服务。这就是我想要的:

这将返回JSON/XML格式的结果

这将返回一条自定义错误消息,而不是标准的“未找到端点”。错误


我阅读了关于IErrorHandler接口和扩展WebHttpBehavior类的内容。但不起作用。

最简单的方法是定义处理“未找到”案例的操作-使用“*”的UriTemplate(如果没有其他模板与传入请求匹配,它将匹配)。下面的代码显示了一个示例

public class Post_0424d917_89cd_43c8_be70_5d4c6934b48c
{
    [ServiceContract]
    public interface ITest
    {
        [WebGet(UriTemplate = "/Echo?text={text}")]
        string EchoGet(string text);
        [WebInvoke(UriTemplate = "/Echo")]
        string EchoPost(string text);
        [WebGet(UriTemplate = "*")]
        Stream ErrorForGet();
        [WebInvoke(UriTemplate = "*")]
        Stream ErrorForPost();
    }
    public class Service : ITest
    {
        public string EchoGet(string text) { return text; }
        public string EchoPost(string text) { return text; }
        public Stream ErrorForPost() { return this.ErrorForGet(); }
        public Stream ErrorForGet()
        {
            WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.NotFound;
            WebOperationContext.Current.OutgoingResponse.ContentType = "text/html";
            string result = @"<html>
  <head>
    <title>Resource not found</title>
  </head>
  <body>
    <h1>This resource cannot be found</h1>
  </body>
</html>";
            return new MemoryStream(Encoding.UTF8.GetBytes(result));
        }
    }
    static void SendRequest(string uri, string method, string contentType, string body)
    {
        HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uri);
        req.Method = method;
        if (!String.IsNullOrEmpty(contentType))
        {
            req.ContentType = contentType;
        }

        if (body != null)
        {
            byte[] bodyBytes = Encoding.UTF8.GetBytes(body);
            req.GetRequestStream().Write(bodyBytes, 0, bodyBytes.Length);
            req.GetRequestStream().Close();
        }

        HttpWebResponse resp;
        try
        {
            resp = (HttpWebResponse)req.GetResponse();
        }
        catch (WebException e)
        {
            resp = (HttpWebResponse)e.Response;
        }

        Console.WriteLine("HTTP/{0} {1} {2}", resp.ProtocolVersion, (int)resp.StatusCode, resp.StatusDescription);
        foreach (string headerName in resp.Headers.AllKeys)
        {
            Console.WriteLine("{0}: {1}", headerName, resp.Headers[headerName]);
        }

        Console.WriteLine();
        Console.WriteLine(new StreamReader(resp.GetResponseStream()).ReadToEnd());

        Console.WriteLine();
        Console.WriteLine("  *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*  ");
        Console.WriteLine();
    }
    public static void Test()
    {
        string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
        ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
        host.AddServiceEndpoint(typeof(ITest), new WebHttpBinding(), "").Behaviors.Add(new WebHttpBehavior());
        host.Open();
        Console.WriteLine("Host opened");

        SendRequest(baseAddress + "/Echo?text=hello", "GET", null, null);
        SendRequest(baseAddress + "/Echo", "POST", "application/json", "\"world\"");

        SendRequest(baseAddress + "/NotFound", "GET", null, null);
        SendRequest(baseAddress + "/NotFound", "POST", "text/xml", "<body/>");

        Console.Write("Press ENTER to close the host");
        Console.ReadLine();
        host.Close();
    }
}
public class Post_0424d917_89cd_43c8_be70_5d4c6934b48c
{
[服务合同]
公共接口测试
{
[WebGet(UriTemplate=“/Echo?text={text}”)]
字符串EchoGet(字符串文本);
[WebInvoke(UriTemplate=“/Echo”)]
字符串EchoPost(字符串文本);
[WebGet(UriTemplate=“*”)]
流错误忘记();
[WebInvoke(UriTemplate=“*”)]
Stream ErrorForPost();
}
公共类服务:ITest
{
公共字符串EchoGet(字符串文本){返回文本;}
公共字符串EchoPost(字符串文本){返回文本;}
公共流ErrorForPost(){返回this.ErrorForForPost();}
公共流错误忘记()
{
WebOperationContext.Current.OutgoingResponse.StatusCode=HttpStatusCode.NotFound;
WebOperationContext.Current.OutgoingResponse.ContentType=“text/html”;
字符串结果=@“
找不到资源
找不到此资源
";
返回新的MemoryStream(Encoding.UTF8.GetBytes(result));
}
}
静态void SendRequest(字符串uri、字符串方法、字符串内容类型、字符串正文)
{
HttpWebRequest req=(HttpWebRequest)HttpWebRequest.Create(uri);
要求方法=方法;
如果(!String.IsNullOrEmpty(contentType))
{
req.ContentType=ContentType;
}
if(body!=null)
{
byte[]bodyBytes=Encoding.UTF8.GetBytes(body);
req.GetRequestStream().Write(bodyBytes,0,bodyBytes.Length);
req.GetRequestStream().Close();
}
HttpWebResponse resp;
尝试
{
resp=(HttpWebResponse)req.GetResponse();
}
捕获(WebE例外)
{
resp=(HttpWebResponse)e.Response;
}
WriteLine(“HTTP/{0}{1}{2}”,resp.ProtocolVersion,(int)resp.StatusCode,resp.StatusDescription);
foreach(分别在header.allkey中的字符串headerName)
{
WriteLine(“{0}:{1}”,headerName,resp.header[headerName]);
}
Console.WriteLine();
Console.WriteLine(新的StreamReader(resp.GetResponseStream()).ReadToEnd());
Console.WriteLine();
Console.WriteLine(“*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*”;
Console.WriteLine();
}
公共静态无效测试()
{
string baseAddress=“http://“+Environment.MachineName+”:8000/服务”;
ServiceHost主机=新ServiceHost(类型(服务),新Uri(基地址));
host.AddServiceEndpoint(typeof(ITest),new-WebHttpBinding(),“”)。Behaviors.Add(new-WebHttpBehavior());
host.Open();
Console.WriteLine(“主机已打开”);
SendRequest(baseAddress+“/Echo?text=hello”、“GET”、null、null);
SendRequest(baseAddress+“/Echo”、“POST”、“application/json”、“world\”);
SendRequest(baseAddress+“/NotFound”、“GET”、null、null);
SendRequest(baseAddress+“/NotFound”、“POST”、“text/xml”、““”);
控制台。写入(“按ENTER键关闭主机”);
Console.ReadLine();
host.Close();
}
}