【发布时间】:2011-12-19 22:15:02
【问题描述】:
我在 C# 中有一个典型的 WCF REST 服务,它接受 JSON 输入并返回 JSON 输出:
[ServiceContract]
public class WCFService
{
[WebInvoke(Method = "POST", UriTemplate = "register", ResponseFormat = WebMessageFormat.Json)]
public BasicResponse RegisterNewUser(UserDTO newUser)
{
return new BasicResponse()
{ status = "ERR_USER_NAME" };
}
}
public class BasicResponse
{
public string status { get; set; }
}
public class UserDTO
{
public string username { get; set; }
public string authCode { get; set; }
}
这按预期工作,但我想在正常执行和出错的情况下返回不同的对象。我创建了一个基本响应类和几个继承者。现在 WCF JSON 序列化程序崩溃并产生“400 Bad Request”:
[ServiceContract]
public class WCFService
{
[WebInvoke(Method = "POST", UriTemplate = "register",
ResponseFormat = WebMessageFormat.Json)]
public BasicResponse RegisterNewUser(UserDTO newUser)
{
return new ErrorResponse()
{
status = "ERR_USER_NAME",
errorMsg = "Invalid user name."
};
}
}
public class BasicResponse
{
public string status { get; set; }
}
public class ErrorResponse : BasicResponse
{
public string errorMsg { get; set; }
}
public class UserDTO
{
public string username { get; set; }
public string authCode { get; set; }
}
我尝试应用 [KnownType(typeof(ErrorResponse))] 和 [ServiceKnownType(typeof(ErrorResponse))] 属性但没有成功。似乎是 DataContractJsonSerializer 中的一个错误,它声明它支持多态性。
我的 WCF REST 服务使用 WebServiceHostFactory:
<%@ ServiceHost Language="C#" Debug="true"
Service="WCFService"
CodeBehind="CryptoCharService.svc.cs"
Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>
在我的 Web.config 中,我有标准的 HTTP 端点:
<system.serviceModel>
<standardEndpoints>
<webHttpEndpoint>
<standardEndpoint helpEnabled="true" defaultOutgoingResponseFormat="Json" />
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>
你认为这是可以解决的吗?我知道一种解决方法(返回字符串并手动序列化输出),但为什么这不起作用?
【问题讨论】:
标签: c# wcf json polymorphism