我正在制作一个 web api 项目,我注意到我的一个方法在我尝试使用 xml 时死了。我通常在测试时只使用 json,因为这是我的首选方法,而且效果很好。
public HttpResponseMessage GetStoreNames(StoreDm vm)
{
if (ModelState.IsValid)
{
var result = storeService.AutoCompleteStore(vm.Latitude, vm.Longitude, vm.Name);
return Request.CreateResponse <ResponseResult<AutoCompleteSearchDto>>(result.Status.Code, result);
}
var responseResult = new ResponseResultWrapper();
responseResult.Status.Code = HttpStatusCode.BadRequest;
responseResult.Status.Message = GenericErrors.InvalidRequest;
responseResult.ModelStateToResponseResult(ModelState);
return Request.CreateResponse<ResponseResult>(responseResult.Status.Code, responseResult);
}
[DataContract(Name = "MyRoot")]
public class ResponseResultWrapper : ResponseResult
{
public void ModelStateToResponseResult(ModelStateDictionary modelState)
{
foreach (var kvp in modelState)
{
foreach (var error in kvp.Value.Errors)
{
string key = kvp.Key;
string msg = error.ErrorMessage;
if (String.IsNullOrEmpty(msg))
{
msg = error.Exception.Message;
}
base.AddError(key, msg);
}
}
}
}
[DataContract(Name = "MyRoot")]
public class ResponseResult
{
public ResponseResult()
{
Errors = new Dictionary<string, string>();
Status = new ResponseBase();
}
public void AddError(string key, string errorMessage)
{
if (!Errors.ContainsKey(key))
{
Errors.Add(key, errorMessage);
}
}
public bool IsValid()
{
if (Errors.Count > 0)
{
return false;
}
return true;
}
[DataMember]
public Dictionary<string, string> Errors { get; private set; }
[DataMember]
public ResponseBase Status { get; set; }
}
[DataContract(Name = "MyRoot")]
public class ResponseResult<T> : ResponseResult
{
[DataMember]
public T Response { get; set; }
}
我收到这个错误
HTTP/1.1 500 Internal Server Error
Cache-Control: private
Content-Type: application/xml; charset=utf-8
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?QzpcVXNlcnNcV2luZG93czdcRGVza3RvcFxQcmljZUNoZWNrXHRydW5rXFByaWNlQ2hlY2tcUHJpY2VDaGVjay5BcGlcYXBpXHN0b3JlXEdldFN0b3JlTmFtZXM=?=
X-Powered-By: ASP.NET
Date: Thu, 23 May 2013 16:44:14 GMT
Content-Length: 2195
<Error><Message>An error has occurred.</Message><ExceptionMessage>The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.</ExceptionMessage><ExceptionType>System.InvalidOperationException</ExceptionType><StackTrace /><InnerException><Message>An error has occurred.</Message><ExceptionMessage>Type 'ResponseResultWrapper' with data contract name 'http://schemas.datacontract.org/2004/07/Api.Models' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.</ExceptionMessage><ExceptionType>System.Runtime.Serialization.SerializationException</ExceptionType><StackTrace> at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeAndVerifyType(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, Boolean verifyKnownType, RuntimeTypeHandle declaredTypeHandle, Type declaredType)
at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithXsiTypeAtTopLevel(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle originalDeclaredTypeHandle, Type graphType)
at System.Runtime.Serialization.DataContractSerializer.InternalWriteObjectContent(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver)
at System.Runtime.Serialization.DataContractSerializer.InternalWriteObject(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver)
at System.Runtime.Serialization.XmlObjectSerializer.WriteObjectHandleExceptions(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver)
at System.Runtime.Serialization.DataContractSerializer.WriteObject(XmlWriter writer, Object graph)
at System.Net.Http.Formatting.XmlMediaTypeFormatter.<>c__DisplayClass7.<WriteToStreamAsync>b__6()
at System.Threading.Tasks.TaskHelpers.RunSynchronously(Action action, CancellationToken token)</StackTrace></InnerException></Error>
编辑
[DataContract]
public class StoreDm
{
[DataMember(IsRequired = true)]
[MinLength(3)]
public string Name { get; set; }
[DataMember(IsRequired = true)]
public double Latitude { get; set; }
[DataMember(IsRequired = true)]
public double Longitude { get; set; }
}
在尝试“Youssef Moussaoui”他的答案的第一部分后,我得到了这个错误。
There was an error deserializing the object of type StoreDm. The data at the root level is invalid. Line 1, position 1.
我真的不能做他的第二部分,因为“ResponseResultWrapper”和“ResponeResult”在两个不同的库中。