环境:Web Api 返回值类型为DTO实体,继承基类DTO---BaseResultDto
public class BaseResultDto { /// <summary> /// 结果代码 /// </summary> [XmlElement("result")] public int Result { get; set; } /// <summary> /// 结果信息 /// </summary> [XmlElement("message")] public string Message { get; set; } /// <summary> /// 构造函数 /// </summary> public BaseResultDto() { this.Result = ResponseCode.SUCCESS; this.Message = string.Empty; } /// <summary> /// 构造函数 /// </summary> /// <param name="result"></param> /// <param name="message"></param> public BaseResultDto(int result, string message) { this.Result = result; this.Message = message; } }
背景:在执行每个Action前先执行筛选器操作,在筛选中,如果报错,无法返回当前Action的返回值类型,如果都返回基类DTO,客户端无法解析当前Action的DTO名称(他们比较懒。。。)所以准备在筛选器中,截获当前请求的方法返回值类型,并在筛选报错的情况下返回。
public override void OnActionExecuting(HttpActionContext actionContext)
{ string retClass = actionContext.ActionDescriptor.ReturnType.AssemblyQualifiedName;
Type t;
object obj; t = Type.GetType(retClass);//通过string类型的retClass获得同名类“t”
if (t == null) { return;
}
obj = t.CreateInstance();
if (!WebConfig.GetEBOpenCity.Contains(city))
{
if (!obj.TrySetValue("message", "电商尚未开通该城市"))
{ return;
}
responseMessage.StatusCode = HttpStatusCode.OK;
responseMessage.Content = new ObjectContent(t, obj, new CustomXmlFormatter()); actionContext.Response = responseMessage; return;
} }
这样如果我请求的方法是:
public MyTradeListDTO GetMyTradeList(string mobile, int pageIndex, int pageSize) { //... }
其中MyTradeListDTO继承BaseResultDto,如果在筛选器中报错,返回的是:
<MyTradeListDTO> <result>-99</result> <message>电商尚未开通该城市</message> <Count>0</Count> </MyTradeListDTO>
这样方便客户端解析了