我在使用 WCF 4.0 RESTful 服务时遇到了令人兴奋的问题。我正在尝试创建一个休息服务,如果出现错误,它将返回一个描述问题的 xml 文档
前任 :
<ErrorHandler>
<cause>Resource not available</cause>
<errorCode>111103</errorCode>
</ErrorHandler>
为了做到这一点,我使用 Visual Studio 提供的模板创建了一个默认的 REST 服务
这是我的服务类别:
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; }
}
}
疯狂的是,这个东西可以工作,但不能:))。我想说的是,Visual Studio 给我一个错误,指出用户代码未捕获 WebFaultException :|它暂停了我的应用程序。如果我按继续,一切都会正常进行。
以下是一些描述我的问题的图片:
小提琴手的第一步:第一步 http://i130.photobucket.com/albums/p245/dreamer_prime/Step1.png
接下来 Visual Studio 的错误:Visual Studio 错误 http://i130.photobucket.com/albums/p245/dreamer_prime/Error.png
最后按继续后一切正常:
这对我来说毫无意义,我不知道为什么会发生这种情况以及如何解决它:P。我在网上搜索了好几天试图找到解决方案但没有运气。我正在使用 Visual Studio 2010 Ultimate
此致 :)