开始的地方是堆栈跟踪,它指示发生异常的位置:
at System.Xml.Serialization.XmlSchemaExporter.ExportElement(ElementAccessor accessor)
at System.Xml.Serialization.XmlSchemaExporter.ExportTypeMapping(XmlTypeMapping xmlTypeMapping)
at System.Web.Services.Description.MimeXmlReflector.ReflectReturn()
at System.Web.Services.Description.HttpProtocolReflector.ReflectMimeReturn()
at System.Web.Services.Description.HttpPostProtocolReflector.ReflectMethod()
通过使用ILSpy,我们可以观察触发异常的条件:
// System.Xml.Serialization.XmlSchemaExporter
private XmlSchemaElement ExportElement(ElementAccessor accessor)
{
if (!accessor.Mapping.IncludeInSchema && !accessor.Mapping.TypeDesc.IsRoot)
{
return null;
}
if (accessor.Any && accessor.Name.Length == 0)
{
throw new InvalidOperationException(Res.GetString("XmlIllegalWildcard"));
}
// truncated method body
}
进一步浏览代码:
// System.Web.Services.Description.MimeXmlReflector
internal override bool ReflectReturn()
// System.Xml.Serialization.XmlReflectionImporter
private ElementAccessor
ImportElement(TypeModel model,
XmlRootAttribute root,
string defaultNamespace,
RecursionLimiter limiter)
依此类推,我们得到这个方法:
// System.Xml.Serialization.XmlReflectionImporter
private static ElementAccessor
CreateElementAccessor(TypeMapping mapping, string ns)
{
ElementAccessor elementAccessor = new ElementAccessor();
bool flag = mapping.TypeDesc.Kind == TypeKind.Node;
if (!flag && mapping is SerializableMapping)
{
flag = ((SerializableMapping)mapping).IsAny;
}
if (flag)
{
elementAccessor.Any = true;
}
else
{
elementAccessor.Name = mapping.DefaultElementName;
elementAccessor.Namespace = ns;
}
// truncated
}
似乎XElement
类型映射将Any
属性值设置为true
但没有得到DefaultElementName
.
该问题的一个简单解决方法是创建一个派生类:
public class FooBarService : System.Web.Services.WebService
{
[WebMethod]
public MyXElement Foo(string bar)
{
return null;
}
}
public class MyXElement : XElement
{
public MyXElement()
: base(XName.Get("default")) { }
}
这将在堆栈中调用:
System.Web.Services.Description.SoapProtocolReflector.ReflectMethod()
而不是HttpPostProtocolReflector.ReflectMethod()
方法和名称被正确分配:
messagePart.Name = members[0].MemberName;
回答你的问题,当你将 赋值XElement
为参数时,方法调用起作用的原因是因为类型映射是通过其他方法创建的,并且name
成员不为空。所以引发异常的条件不会发生。