有没有更好的方法将标准的“无效的用户名/密码”消息返回给连接到需要凭据的WCF服务的客户端?我有以下代码,当我使用无效的用户名/密码连接到我的WCF服务时会导致异常。
理想情况下,我只想返回一个简单的字符串,但是要让UsernamePasswordValidator指示错误的用户名,需要抛出 FaultException 或 SecurityTokenException ,这会导致异常HttpWebRequest的GetResponse方法的客户端。
FileInfo file = new FileInfo("Request.xml");
string payload = file.OpenText().ReadToEnd();
HttpWebRequest request = HttpWebRequest.Create(URL) as HttpWebRequest;
request.ContentType = "text/xml";
request.ContentLength = payload.Length;
request.MediaType = "utf-8";
request.Method = "POST";
StreamWriter writer = new StreamWriter(request.GetRequestStream());
writer.Write(payload);
writer.Flush();
writer.Close();
Console.WriteLine("Awaiting Response...");
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
StreamReader reader = new StreamReader(response.GetResponseStream());
Console.WriteLine(reader.ReadToEnd());
Console.ReadKey(true);
我想这样做的原因是服务将受到不使用.NET的客户端的攻击。</ p>
答案 0 :(得分:2)
将它放在try - catch
语句中并捕获异常,然后在catch块中传递您自己的消息