C#Wcf Web API反序列化响应
问题描述:
我想单元测试一个返回非原语的Web服务。根据请求,响应可以是xml或json。在我的测试中,如果我可以将内容主体反序列化为我的一个对象,那将会很棒。下面是一些代码:C#Wcf Web API反序列化响应
[WebGet(UriTemplate = "{arg1}/{arg2}")]
public HttpResponseMessage<MyType> GetSomethingCool(string arg1, long arg2)
{
return new HttpResonseMessage<MyTpe>(new MyType());
}
public class MyType
{
public string Property1 { get; set; }
public long Property2 { get; set; }
public string Property3 { get; set; }
}
而且我的测试:
[Test]
public void MyTestForTheWebService_ReturnsText()
{
Service1 service = new Service1 (_mockRepository.Object);
HttpResponseMessage<MyType> result = service.GetSomethingCool("Something", **);
Assert.AreEqual(HttpStatusCode.OK, result.StatusCode);
MyType resultContent = result.Content.ReadAs<MyType>(); // doesn't work
Assert.AreEqual("expected value", resultContent .Property1);
.....
所以基本上我需要能够把result.Content到MyType的,不知道怎么办。由于
答
尝试做:
MyType resultContent = (MyType)result.Content.ReadAs();
我相信你正在运行到一个已知的bug。
太棒了,作品像一个魅力。我认为我的代码应该可以工作,但这是一个错误,将在未来版本中修复? – 2011-06-11 20:46:53
@nextgenneo正好。 – 2011-06-11 20:49:24
@NoahHeldman不在我的副本中,它没有。它位于HttpContentExtensionMethods类中。 – 2011-09-28 01:14:48