我正在尝试找出一种使用 ASP.NET WebApi 返回具有非 200 返回代码的自定义负载的方法。基本上我想拥有
{"status":{"code":"40001", "message": "Field XXX can not be empty"}}
和
<status><code>40001</code><message>Field XXX can not be empty</message></status>
我正在使用 HttpError
类来完成此操作,方法是添加带有所需负载的 Dictionary
。它适用于 JSON,但不适用于 XML,据我了解,它归结为 XmlSerializer
和 HttpError
播放不佳。
这里是重现完全相同错误的简短代码片段:
var error = new HttpError();
var status = new Dictionary<string, string>
{
{"code", "40001"},
{"text", "Field XXX can not be empty"}
};
error.Add("status", status);
var ser = new XmlSerializer(error.GetType());
StringWriter strWriter = new StringWriter();
ser.Serialize(strWriter, error);
在这种情况下,我得到 Xml type 'xdt:untypedAtomic' does not support a conversion from Clr type 'KeyValuePair 2' to Clr type 'String'
下一步是意识到 KeyValuePair
不可序列化,并创建单独的类:
[XmlType(TypeName="Status")]
public class ResponseStatus
{
public ResponseStatus(){}
public String Code
{ get; set; }
public String Text
{ get; set; }
}
它本身可以很好地序列化,但如果在 HttpError 中使用,则会抛出完全相同的异常:
Xml 类型“List of xdt:untypedAtomic”不支持从 Clr 类型“ResponseStatus”到 Clr 类型“String”的转换。
我不相信以前没有人这样做过,所以我想知道我错过了什么?
最佳答案
你也可以这样做;
HttpError err = new HttpError();
err["code"] = "40001";
err["text"] = "Field XXX can not be empty";
然后在 Controller 级别通过 HttpResponseMessage 返回它,即
return Request.CreateResponse(HttpStatusCode.--, err);
为了返回 {"status":{"code":"40001", "message": "Field XXX can not be empty"}},你可能需要创建一个复杂的类型,即
public class ResponseStatus
{
public Status status { get; set; }
}
public class Status
{
public string code { get; set; }
public string message { get; set; }
}
然后从你的 Controller 中实例化这两个类
Status st = new Status();
st.code = "40001";
st.message = "Field XXX can not be empty";
ResponseStatus responsStatus = new ResponseStatus();
responsStatus.status = st;
return Request.CreateResponse(HttpStatusCode.OK, responsStatus);
为了更好地控制您的输出,请考虑使用 DataContract 装饰您的类和 DataMember对于属性。来自这些命名空间 System.ComponentModel.DataAnnotations 并使用 System.Runtime.Serialization ie
[DataContract]
class Status
{
[DataMember(Name = "code")]
public string code { get; set; }
[DataMember(Name = "message")]
public string message { get; set; }
}
关于c# - WebApi 中带有自定义负载的 HttpError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22538440/