当我将使用泛型类型的返回对象序列化为 XML 时,我的 REST API 出现错误。使用 JSON 时不会重现此错误。
这是一个演示我的问题的简化示例:
using System;
using System.Net;
using System.Net.Http;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using System.Web.Http;
namespace Areas.API
{
public abstract class AnimalController<TProperties> : ApiController
where TProperties : new()
{
protected abstract TProperties makeNew( Int32 Id );
[Route( "{id}" )]
public AnimalReturn<TProperties> Get( Int32 id )
{
TProperties p = makeNew( id );
return new AnimalReturn<TProperties>()
{
Properties = p,
Request = Request,
StatusCode = HttpStatusCode.OK
};
}
}
public class AnimalReturn<TProperties> : AnimalResult
{
public TProperties Properties;
}
public class AnimalResult : IHttpActionResult
{
[IgnoreDataMember]
public HttpStatusCode StatusCode = HttpStatusCode.OK;
[IgnoreDataMember]
public HttpRequestMessage Request = null;
public Task<HttpResponseMessage> ExecuteAsync( System.Threading.CancellationToken cancellationToken )
{
HttpResponseMessage response = null;
if( null != Request )
{
response = Request.CreateResponse( StatusCode, this );
}
return Task.FromResult( response );
} // ExecuteAsync()
}
[RoutePrefix( "api/v3/Fish" )]
public class FishController : AnimalController<FishController.FishProperties>
{
public class FishProperties
{
public bool IsShark;
}
protected override FishProperties makeNew( Int32 Id )
{
return new FishProperties()
{
IsShark = true
};
}
}
[RoutePrefix( "api/v3/Dog" )]
public class DogController : AnimalController<DogController.DogProperties>
{
public class DogProperties
{
public string Breed;
public Int32 TagNo;
}
protected override DogProperties makeNew( Int32 Id )
{
return new DogProperties()
{
Breed = "Labrador",
TagNo = 12345
};
}
}
}
当我运行此 API 调用时:
localhost/api/v3/Dog/1
带标题
Accept: text/xml
我收到这个错误:
<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 'Areas.API.AnimalReturn`1[[Areas.API.DogController+DogProperties, NbtWebApp, Version=2012.2.4.1, Culture=neutral, PublicKeyToken=null]]' with data contract name 'AnimalReturnOfDogController.DogPropertiesS2PP9ThI:http://schemas.datacontract.org/2004/07/Areas.API' 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.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content)
at System.Net.Http.Formatting.XmlMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.WebHost.HttpControllerHandler.<WriteBufferedResponseContentAsync>d__1b.MoveNext()</StackTrace>
</InnerException>
</Error>
但是,当我删除继承(注意 AnimalReturn2)时,问题就消失了:
using System;
using System.Net;
using System.Net.Http;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using System.Web.Http;
namespace Areas.API
{
public abstract class AnimalController<TProperties> : ApiController
where TProperties : new()
{
protected abstract TProperties makeNew( Int32 Id );
[Route( "{id}" )]
public AnimalReturn2<TProperties> Get( Int32 id )
{
TProperties p = makeNew( id );
return new AnimalReturn2<TProperties>()
{
Properties = p,
Request = Request,
StatusCode = HttpStatusCode.OK
};
}
}
public class AnimalReturn2<TProperties> : IHttpActionResult
{
public TProperties Properties;
[IgnoreDataMember]
public HttpStatusCode StatusCode = HttpStatusCode.OK;
[IgnoreDataMember]
public HttpRequestMessage Request = null;
public Task<HttpResponseMessage> ExecuteAsync( System.Threading.CancellationToken cancellationToken )
{
HttpResponseMessage response = null;
if( null != Request )
{
response = Request.CreateResponse( StatusCode, this );
}
return Task.FromResult( response );
} // ExecuteAsync()
}
[RoutePrefix( "api/v3/Fish" )]
public class FishController : AnimalController<FishController.FishProperties>
{
public class FishProperties
{
public bool IsShark;
}
protected override FishProperties makeNew( Int32 Id )
{
return new FishProperties()
{
IsShark = true
};
}
}
[RoutePrefix( "api/v3/Dog" )]
public class DogController : AnimalController<DogController.DogProperties>
{
public class DogProperties
{
public string Breed;
public Int32 TagNo;
}
protected override DogProperties makeNew( Int32 Id )
{
return new DogProperties()
{
Breed = "Labrador",
TagNo = 12345
};
}
}
}
现在,当我运行相同的请求时,我得到:
<AnimalReturn2OfDogController.DogPropertiesS2PP9ThI
xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://schemas.datacontract.org/2004/07/Areas.API">
<Properties>
<Breed>Labrador</Breed>
<TagNo>12345</TagNo>
</Properties>
</AnimalReturn2OfDogController.DogPropertiesS2PP9ThI>
问题是:有没有办法在仍然使用继承的情况下解决 XML 序列化问题?
我已经尝试在不同的地方和不同的组合使用 KnownTypes(如此处建议:Unexpected Type - Serialization Exception 和此处:"Type not expected", using DataContractSerializer - but it's just a simple class, no funny stuff?),但我仍然怀疑那里有一个简单的答案。
我也试过禁用代理类,但这似乎没有帮助。
谢谢。
最佳答案
序列化是在基类方法内部完成的 AnimalResult.ExecuteAsync() ,正在调用 HttpRequestMessageExtensions.CreateResponse<T> Method (HttpRequestMessage, HttpStatusCode, T) :
response = Request.CreateResponse( StatusCode, this );
自 this静态类型为 AnimalResult ,此类型成为通用参数 T传递给扩展方法。因此,尝试将派生的类型添加为 KnownType AnimalResult 的属性:
[KnownType(typeof(AnimalReturn<DogController.DogProperties>))]
[KnownType(typeof(AnimalReturn<FishController.FishProperties>))]
public class AnimalResult : IHttpActionResult
{
}
您还应该能够通过使用 MakeGenericMethod() 使其正常工作调用HttpRequestMessageExtensions.CreateResponse<T>与 this.GetType()作为类型参数。参见 How to invoke static generic class methods if the generic type parameters are unknown until runtime?
更新
这是一个示例,说明如何使用 AnimalResult 的实际类型在运行时调用静态泛型方法。被返回,从而避免需要定义 AnimalResult 的所有可能的派生类作为已知类型:
public class AnimalResult : IHttpActionResult
{
[IgnoreDataMember]
public HttpStatusCode StatusCode = HttpStatusCode.OK;
[IgnoreDataMember]
public HttpRequestMessage Request = null;
private static HttpResponseMessage StaticCreateResponse<TAnimalResult>(TAnimalResult animalResult) where TAnimalResult : AnimalResult
{
if (animalResult == null)
throw new ArgumentNullException(); // Should have been checked outside.
Debug.Assert(typeof(TAnimalResult) == animalResult.GetType());
return animalResult.Request.CreateResponse(animalResult.StatusCode, animalResult);
}
HttpResponseMessage CreateResponse()
{
if (Request == null)
return null;
else
{
var method = typeof(AnimalResult).GetMethod("StaticCreateResponse", BindingFlags.NonPublic | BindingFlags.Static);
var genericMethod = method.MakeGenericMethod(new[] { GetType() });
return (HttpResponseMessage)genericMethod.Invoke(null, new object[] { this });
}
}
public Task<HttpResponseMessage> ExecuteAsync( CancellationToken cancellationToken )
{
var response = CreateResponse();
return Task.FromResult( response );
} // ExecuteAsync()
}
关于c# - 使用泛型类型和继承时在 REST API 上序列化 XML 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32484810/
我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div
我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看rubyzip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
很好奇,就使用rubyonrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提
假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于
我正在尝试使用ruby和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t
我正在用Ruby编写一个简单的程序来检查域列表是否被占用。基本上它循环遍历列表,并使用以下函数进行检查。require'rubygems'require'whois'defcheck_domain(domain)c=Whois::Client.newc.query("google.com").available?end程序不断出错(即使我在google.com中进行硬编码),并打印以下消息。鉴于该程序非常简单,我已经没有什么想法了-有什么建议吗?/Library/Ruby/Gems/1.8/gems/whois-2.0.2/lib/whois/server/adapters/base.
我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h