无论我怎么努力,我似乎无法在Silverlight中处理WCF故障。 事实上,错误似乎永远不会离开服务器!
E.g。当我调试它时,它会在我抛出FaultException的行上停止,说它没有被处理:
[SilverlightFaultBehavior]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class StoreService : IStoreContract
{
public System.Collections.Generic.List<string> GetStoreDesignNames()
{
try
{
StoreDataContext swdc = new StoreDataContext();
var query = from storeDesign in swdc.StoreDesignDBs select storeDesign.Name;
return query.ToList();
}
catch (System.Data.SqlClient.SqlException sqlExcept)
{
throw new FaultException<SqlFault>(new SqlFault() { Message = sqlExcept.Message });
}
}
}
实现此方法的类派生自契约接口:
[ServiceContract(Namespace = "Store")]
public interface IStoreContract
{
/// <summary>
/// Obtain the list of store design names.
/// </summary>
[OperationContract,
FaultContract(typeof(SqlFault))]
List<String> GetStoreDesignNames();
}
SqlFault类的定义如下:
public class SqlFault
{
public String Message { get; set; }
}
在客户端,我处理错误如下:
// swc is the client
swc.GetStoreDesignNamesCompleted += new EventHandler<ServiceReference.GetStoreDesignNamesCompletedEventArgs>((obj, evt) =>
{
if (evt.Error == null)
{
// In case of success
MessageBox.Show(evt.Result.First());
}
else if (evt.Error is FaultException<ServiceReference.SqlFault>)
{
FaultException<ServiceReference.SqlFault> fault = evt.Error as FaultException<ServiceReference.SqlFault>;
Dispatcher.BeginInvoke(() =>
{
ErrorWindow ew = new ErrorWindow(fault.Detail.Message, "No details");
ew.Show();
});
}
});
swc.GetStoreDesignNamesAsync();
我试图在界面上放置[SilverlightFaultBehavior]属性,但无济于事。即使我没有接口,我仍然有这个错误。
我还尝试在web.config中使用行为扩展名为described here,但我收到一条警告,说扩展名无效。
如何在Siverlight中正确处理WCF故障? 提前谢谢。
答案 0 :(得分:1)
我没有使用过WCF(一直使用WCF RIA服务),但我刚才发现过这篇文章。
Getting something better than “Server not found.” from WCF in Silverlight
答案 1 :(得分:0)
经过几个小时的斗争,我终于一起攻击了一些有效的东西。 这真是一个可怕的黑客,我更倾向于使用BehaviorExtension来完成这项任务。诀窍是在WCF方法的主体中手动设置HTTP状态代码,如下所示:
public System.Collections.Generic.List<string> GetStoreDesignNames()
{
try
{
StoreDataContext swdc = new StoreDataContext();
var query = from storeDesign in swdc.StoreDesignDBs select storeDesign.Name;
return query.ToList();
}
catch (System.Data.SqlClient.SqlException sqlExcept)
{
System.ServiceModel.Web.WebOperationContext ctx = System.ServiceModel.Web.WebOperationContext.Current;
ctx.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK;
throw new FaultException<SqlFault>(new SqlFault() { Message = sqlExcept.Message });
}
}
然后在客户端正确显示错误消息。 如果有人有比这更好的解决方案,我想听听。