我在使用WCF 4.0 RESTful服务一个令人兴奋的问题。我试图做一个REST服务,将返回,在出现错误的情况下,一个XML文档描述问题 例如:WCF休息错误处理
<ErrorHandler>
<cause>Resource not available</cause>
<errorCode>111103</errorCode>
</ErrorHandler>
为了使这个我已经创建使用模板默认REST服务由Visual Studio提供 这里是我的服务类:
public class Service1
{
// TODO: Implement the collection resource that will contain the SampleItem instances
[WebGet(UriTemplate = "")]
public List<SampleItem> GetCollection()
{
// TODO: Replace the current implementation to return a collection of SampleItem instances\
// throw new WebException("lala");
throw new WebFaultException<ErrorHandler>(new ErrorHandler { cause = "Resource not available", errorCode = 100 }, System.Net.HttpStatusCode.NotFound);
//return new List<SampleItem>() { new SampleItem() { Id = 1, StringValue = "Hello" } };
}
[WebInvoke(UriTemplate = "", Method = "POST")]
public SampleItem Create(SampleItem instance)
{
// TODO: Add the new instance of SampleItem to the collection
return new SampleItem() { Id = 3, StringValue = "59" };
}
[WebGet(UriTemplate = "{id}")]
public SampleItem Get(string id)
{
// TODO: Return the instance of SampleItem with the given id
throw new NotImplementedException();
}
[WebInvoke(UriTemplate = "{id}", Method = "PUT")]
public SampleItem Update(string id, SampleItem instance)
{
// TODO: Update the given instance of SampleItem in the collection
throw new NotImplementedException();
}
[WebInvoke(UriTemplate = "{id}", Method = "DELETE")]
public void Delete(string id)
{
// TODO: Remove the instance of SampleItem with the given id from the collection
throw new NotImplementedException();
}
}
}
正如你可以从代码中看到上面我在GetCollection方法扔WebFaultException。应该在响应的主体中放入一个“ErrorHandler”对象。 这里是我的ErrorHandler类看起来像:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.Serialization;
namespace WcfRestService1
{
[DataContract]
public class ErrorHandler
{
[DataMember]
public int errorCode { get; set; }
[DataMember]
public string cause { get; set; }
}
}
疯狂的事情是,这个事情的作品,但它down't :))。我想说的是,视觉工作室给我一个错误,说WebFaultException不被用户代码捕获:并暂停我的应用程序。如果我按继续,一切正常,因为它应该。 下面是一些图片说明我的问题:
在提琴手第一步: First Step
下一个Visual Studio的错误:Visual Studio Error
最后按下继续后,一切都工作:
这是没有意义的我和我不知道为什么这件事正在发生,以及如何解决它:P。我在网上搜索了几天,试图找到一个没有运气的解决方案。我使用Visual Studio 2010的最终
最好的问候:)
非常感谢您的回答。目前还不清楚为什么VS 2010将这个例外报告为未处理。 WCF运行时是否捕获到异常?据我了解,除应由运行时捕获,并且和“原因”对象将被序列化,并与指定的HTTP代码返回给客户端。奇怪的是,2008年的比赛并不像这样。我曾经通过抛出Web ProtocolException来报告错误,并且一切都很好(除了客户端不会收到xml的事实)。在升级到vs 2010之后,发生了这种情况。 – Andrei 2011-04-12 15:43:11
我从来没有与2008年合作,所以我不知道,但我不会太多挂在这一点。只要你的网站有效就好。但正如我所说,按Ctrl + Alt + E查看你的VS设置。 – Aliostad 2011-04-12 15:48:20
我会这样做的。但我想要一个更便携的解决方案。我不是唯一一个在这个项目上工作的人,并且要求我的团队中的每个人都使用这种解决方法并不可行:) – Andrei 2011-04-12 16:41:37