gpt4 book ai didi

asp.net-web-api - XML 在 WebApi 中不适用于我 - 与我的数据契约有关

转载 作者:行者123 更新时间:2023-12-02 04:03:02 28 4
gpt4 key购买 nike

我正在制作一个 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.&lt;&gt;c__DisplayClass7.&lt;WriteToStreamAsync&gt;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”位于两个不同的库中。

最佳答案

尝试改变:

return Request.CreateResponse<ResponseResult>(responseResult.Status.Code, responseResult);

return Request.CreateResponse<ResponseResultWrapper>(responseResult.Status.Code, responseResult);

问题在于 DataContractSerializer 需要已知类型来支持继承。您可以在这里了解更多信息:

http://blogs.msdn.com/b/youssefm/archive/2009/04/21/understanding-known-types.aspx

更改 CreateResponse 上的通用参数是最简单的解决方案,但如果您想要序列化 ​​ResponseResult 的派生实例,则需要向 ResponseResult 添加已知类型属性,如下所示:

[DataContract(Name = "MyRoot")]
[KnownType(typeof(ResponseResultWrapper))]
public class ResponseResult
{
}

.

关于asp.net-web-api - XML 在 WebApi 中不适用于我 - 与我的数据契约有关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16719652/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com