我有一个WCF服务应用程序,其方法为
public PersonResponse(PersonRequest request)
{
return new PersonResponse { Id = 1, Name = "Mark" };
}
我有两种不同的反应可能的方法
[DataContract]
public class PersonResponse
{
int id;
string name;
[DataMember]
public int Id
{
get { return id; }
set { id = value; }
}
[DataMember]
public string Name
{
get { return name; }
set { name = value; }
}
}
和
[DataContract]
public class ErrorResponse
{
int errorCode;
string errorText;
[DataMember]
public int? ErrorCode
{
get { return errorCode; }
set { errorCode = value; }
}
[DataMember]
public string ErrorText
{
get { return errorText; }
set { errorText = value; }
}
}
是否可以编写一个方法来返回其中一个响应,但不能同时返回两者?
我可以做一些类似的事情
[DataContract]
public class Response
{
PersonResponse personResponse;
ErrorResponse errorResponse;
[DataMember]
public bool PersonResponse
{
get { return personResponse; }
set { personResponse= value; }
}
[DataMember]
public string ErrorResponse
{
get { return errorResponse; }
set { errorResponse= value; }
}
}
public Response(PersonRequest request)
{
return new Response{ PersonResponse = New PersonResponse { Id = 1, Name = "Mark" }, ErrorResponse = new ErrorResponse { ErrorCode = null, ErrorText = null } };
}
但我只需要返回一种类型的响应,而不是两者都返回。
我试过
public PersonResponse(PersonRequest request)
{
throw new WebFaultException<ErrorResponse>(new ErrorResponse { ErrorCode = 103 ErrorText = "Try again later" }, HttpStatusCode.Conflict);
}
但这样它似乎只返回异常,而不返回ErrorResponse。
我还尝试过向响应添加和接口层,然后将该接口作为响应返回
public interface IResponse {}
[DataContract]
public class PersonResponse : IResponse
{
int id;
string name;
[DataMember]
public int Id
{
get { return id; }
set { id = value; }
}
[DataMember]
public string Name
{
get { return name; }
set { name = value; }
}
}
[DataContract]
public class ErrorResponse : IResponse
{
int errorCode;
string errorText;
[DataMember]
public int? ErrorCode
{
get { return errorCode; }
set { errorCode = value; }
}
[DataMember]
public string ErrorText
{
get { return errorText; }
set { errorText = value; }
}
}
public IResponse(PersonRequest request)
{
return new PersonResponse { Id = 1, Name = "Mark" };
}
但是,当我将此服务添加为对另一个项目id的引用时,不会生成任何响应类型(Iresponse、ErrorResonse或PersonResponse(,并且在尝试调用该方法时抛出错误(异常消息https://ibb.co/Zdsbr9p)
我认为您可以尝试使用FaultContractAttribute。故障契约允许您指定将在SOAP故障中返回的备用响应
示例界面:
[ServiceContract]
interface IService
{
[OperationContract]
[FaultContract(typeof(ErrorResponse))]
PersonResponse GetResponse();
}
服务:
class Service : IService
{
public PersonResponse GetResponse()
{
if (success)
{
return new PersonResponse();
}
else
{
throw new FaultException<ErrorResponse>(new ErrorResponse()
{
ErrorMessage = "Something Happened"
})
}
}
}
然后,客户端可以通过捕获FaultException<ErrorResponse>:
来处理故障
var serviceProxy = new ServiceProxy();
try
{
var dataObj = serviceProxy.GetResponse();
}
catch (FaultException<ErrorResponse> error)
{
ErrorResponse detail = error.Detail;
Console.WriteLine(detail.ErrorMessage);
}
来源:Wcf服务应该如何最好地为相同的方法返回不同的对象
相似性:从WCF服务返回不同的对象(列表或错误类(