我正在使用 ServiceStack,并且在引发错误时无法在 ResponseStatus 中取回错误消息。
我的服务请求/响应是根据 ServiceStack 要求的命名约定命名的。
要求:
namespace DataDictionary.ServiceModel
{
// Create the name of the Web Service (i.e. the Request DTO)
[RestService("/receivables/{id}", "GET")]
[RestService("/years/{year}/processes/{processname}/receivables/{name}", "GET")]
[DataContract]
public class ReceivableRequest
{
[DataMember]
public int id { get; set; }
[DataMember]
public int year { get; set; }
[DataMember]
public string processname { get; set; }
[DataMember]
public string name { get; set; }
}
}
回复:
namespace DataDictionary.ServiceModel
{
[DataContract]
public class ReceivableRequestResponse : IHasResponseStatus
{
public ReceivableRequestResponse()
{
this.ResponseStatus = new ResponseStatus();
}
[DataMember]
public int id { get; set; }
[DataMember]
public string name { get; set; }
[DataMember]
public Uri process { get; set; }
[DataMember]
public Uri year { get; set; }
#region IHasResponseStatus Members
[DataMember]
public ResponseStatus ResponseStatus {get; set;}
#endregion
}
}
服务:
namespace DataDictionary.ServiceInterface
{
// Create the Web Service implementation
public class ReceivableService : RestServiceBase<ReceivableRequest>
{
private readonly IRepository<Receivable> m_receivableRepository;
public ReceivableService(IRepository<Receivable> receivableRepository)
{
m_receivableRepository = receivableRepository;
}
public override object OnGet(ReceivableRequest request)
{
if (request != null && request.id > 0)
{
return GetSpecificReceivable(request.id);
}
}
private object GetSpecificReceivable(int id)
{
Receivable receivable = m_receivableRepository.SingleOrDefault(rec => rec.Id == id);
if (receivable != null)
{
return receivable;
}
else
{
throw new HttpError(HttpStatusCode.NotFound, new ArgumentException(string.Format("Could not find receivable with id {0}.", id)));
}
}
}
}
当我对服务进行单元测试时返回错误消息
[Test]
public void Can_GET_Receivable_Not_Found_Successfully()
{
//given
var year = new Year { Name = 2006 };
IRepository<Year> repository = Kernel.Get<IRepository<Year>>();
repository.Add(year);
var process = new Process { Name = "TEST", Year = year };
year.AddProcess(process);
var receivable = new Receivable { Name = "File1" };
process.AddReceivable(receivable);
repository.Update(year);
var service = Kernel.Get<ReceivableService>();
var request = new ReceivableRequest { year = 2011, processname = "TEST", name = "File1" };
//when
try
{
var entity = (Receivable)service.OnGet(request);
}
//then
catch (HttpError e)
{
e.Message.ShouldEqual("Could not find receivable File1 from process TEST in year 2011.");
e.StatusCode.ShouldEqual(HttpStatusCode.NotFound);
}
}
但是,当我使用 fiddler 发送请求时,我希望错误消息以 JSON 格式返回,状态代码 404 可用但没有错误消息。
如何访问错误消息?