.NET 자동 생성 웹 서비스 클라이언트 : W3.org에서 스키마를 요청하지 않으려면 어떻게해야합니까?
-
03-07-2019 - |
문제
WSDL.exe 도구를 사용하여 WSDL-File에서 자동 생성 된 .NET 웹 서비스 클라이언트가 있습니다.
생성 된 클래스를 처음 인스턴스화하면 W3.org 및 기타 사람들에게 많은 문서를 요청하기 시작합니다. 첫 번째는입니다 http://www.w3.org/2001/xmlschema.dtd
W3.org로 불필요한 트래픽을 일으키고 싶지 않은 것 외에도 인터넷에 연결하지 않고 응용 프로그램을 실행할 수 있어야합니다 (웹 서비스는 "Web-Service"입니다).
누구든지 해결책을 알고 있습니까?
도움이된다면 인터넷이 없을 때 얻는 스택 트레이스가 있습니다.
"An error has occurred while opening external DTD 'http://www.w3.org/2001/XMLSchema.dtd': The remote name could not be resolved: 'www.w3.org'"
at System.Net.HttpWebRequest.GetResponse()
at System.Xml.XmlDownloadManager.GetNonFileStream(Uri uri, ICredentials credentials)
at System.Xml.XmlDownloadManager.GetStream(Uri uri, ICredentials credentials)
at System.Xml.XmlUrlResolver.GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn)
at System.Xml.XmlTextReaderImpl.OpenStream(Uri uri)
at System.Xml.XmlTextReaderImpl.DtdParserProxy_PushExternalSubset(String systemId, String publicId)
at System.Xml.XmlTextReaderImpl.Throw(Exception e)
at System.Xml.XmlTextReaderImpl.DtdParserProxy_PushExternalSubset(String systemId, String publicId)
at System.Xml.XmlTextReaderImpl.DtdParserProxy.System.Xml.IDtdParserAdapter.PushExternalSubset(String systemId, String publicId)
at System.Xml.DtdParser.ParseExternalSubset()
at System.Xml.DtdParser.ParseInDocumentDtd(Boolean saveInternalSubset)
at System.Xml.DtdParser.Parse(Boolean saveInternalSubset)
at System.Xml.XmlTextReaderImpl.DtdParserProxy.Parse(Boolean saveInternalSubset)
at System.Xml.XmlTextReaderImpl.ParseDoctypeDecl()
at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
at System.Xml.XmlTextReaderImpl.Read()
at System.Xml.Schema.Parser.StartParsing(XmlReader reader, String targetNamespace)
at System.Xml.Schema.Parser.Parse(XmlReader reader, String targetNamespace)
at System.Xml.Schema.XmlSchemaSet.ParseSchema(String targetNamespace, XmlReader reader)
at System.Xml.Schema.XmlSchemaSet.Add(String targetNamespace, XmlReader schemaDocument)
at [...]WebServiceClientType..cctor() in [...]
해결책 2
xmlresolver가 필요했습니다 Tamberg의 해결책 잘 작동하지 않았습니다. 다운로드하는 대신 내장 리소스에서 필요한 스키마를 읽는 내 자신의 xmlresolver를 구현하여 해결했습니다.
그건 그렇고 문제는자가 생성 코드와 관련이 없었습니다.
웹 서비스 클라이언트에는 다음과 같은 내용이 포함 된 또 다른 구현 파일이있었습니다.
public partial class [...]WebServiceClientType
{
private static readonly XmlSchemaSet _schema;
static KeyImportFileType()
{
_schema = new XmlSchemaSet();
_schema.Add(null, XmlResourceResolver.GetXmlReader("http://www.w3.org/TR/2002/REC-xmldsig-core-20020212/xmldsig-core-schema.xsd"));
_schema.Add(null, XmlResourceResolver.GetXmlReader("http://www.w3.org/TR/2002/REC-xmlenc-core-20021210/xenc-schema.xsd"));
_schema.Compile();
}
그리고 실패한 것은이 클래스 구성 자였습니다.
다른 팁
xmlreader (또는 xmltextreader)에 액세스 할 수있는 경우 다음을 수행 할 수 있습니다.
XmlReader r = ...
r.XmlResolver = null; // prevent xsd or dtd parsing
안부, 탐버그
여기 내 해결책이 있습니다. XMLURLRESOLVER의 토대를 해결 해야하는 것처럼 .NET 프레임 워크를 통해 누군가가 디버깅을하지 않아도되기를 바랍니다. 로컬 리소스 (RESX 텍스트 파일)에서로드하거나 캐시 또는 XMLURLRESOLVER 기본 동작을 사용합니다.
using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Net;
using System.Net.Cache;
using System.IO;
using System.Resources;
namespace AxureExport {
//
// redirect URL resolution to local resource (or cache)
public class XmlCustomResolver : XmlUrlResolver {
ICredentials _credentials;
ResourceManager _resourceManager;
public enum ResolverType { useDefault, useCache, useResource };
ResolverType _resolverType;
public XmlCustomResolver(ResolverType rt, ResourceManager rm = null) {
_resourceManager = rm != null ? rm : AxureExport.Properties.Resources.ResourceManager;
_resolverType = rt;
}
public override ICredentials Credentials {
set {
_credentials = value;
base.Credentials = value;
}
}
public override object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn) {
object response = null;
if (absoluteUri == null)
throw new ArgumentNullException(@"absoluteUri");
switch (_resolverType) {
default:
case ResolverType.useDefault: // use the default behavior of the XmlUrlResolver
response = defaultResponse(absoluteUri, role, ofObjectToReturn);
break;
case ResolverType.useCache: // resolve resources thru cache
if (!isExternalRequest(absoluteUri, ofObjectToReturn)) {
response = defaultResponse(absoluteUri, role, ofObjectToReturn);
break;
}
WebRequest webReq = WebRequest.Create(absoluteUri);
webReq.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.Default);
if (_credentials != null)
webReq.Credentials = _credentials;
WebResponse wr = webReq.GetResponse();
response = wr.GetResponseStream();
break;
case ResolverType.useResource: // get resource from internal resource
if (!isExternalRequest(absoluteUri, ofObjectToReturn)) {
response = defaultResponse(absoluteUri, role, ofObjectToReturn); // not an external request
break;
}
string resourceName = uriToResourceKey(absoluteUri);
object resource = _resourceManager.GetObject(resourceName);
if (resource == null)
throw new ArgumentException(@"Resource not found. Uri=" + absoluteUri + @" Local resourceName=" + resourceName);
if (resource.GetType() != typeof(System.String))
throw new ArgumentException(resourceName + @" is an unexpected resource type. (Are you setting resource FileType=Text?)");
response = ObjectToUTF8Stream(resource);
break;
}
return response;
}
//
// convert object to stream
private static object ObjectToUTF8Stream(object o) {
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream, Encoding.UTF8);
writer.Write(o);
writer.Flush();
stream.Position = 0;
return stream;
}
//
// default response is to call tbe base resolver
private object defaultResponse(Uri absoluteUri, string role, Type ofObjectToReturn) {
return base.GetEntity(absoluteUri, role, ofObjectToReturn);
}
//
// determine whether this is an external request
private static bool isExternalRequest(Uri absoluteUri, Type ofObjectToReturn) {
return absoluteUri.Scheme == @"http" && (ofObjectToReturn == null || ofObjectToReturn == typeof(Stream));
}
//
// translate uri to format compatible with reource manager key naming rules
// see: System.Resources.Tools.StronglyTypedResourceBuilder.VerifyResourceName Method
// from http://msdn.microsoft.com/en-us/library/ms145952.aspx:
private static string uriToResourceKey(Uri absoluteUri) {
const string repl = @"[ \xA0\.\,\;\|\~\@\#\%\^\&\*\+\-\/\\\<\>\?\[\]\(\)\{\}\" + "\"" + @"\'\:\!]+";
return Regex.Replace(Path.GetFileNameWithoutExtension(absoluteUri.LocalPath), repl, @"_");
}
}
}
감사합니다 Tamberg, 당신은 당신의 간결하고 정답으로 많은 시간을 절약했습니다. 기본 리졸버가 웹에 갈 것이라는 것을 몰랐습니다. MSDN을 확인하는 것은 상태입니다.
XMLRESOLVER는 System.XML 네임 스페이스의 모든 클래스의 기본 레졸버입니다. 당신은 또한 자신만의 리졸버를 만들 수 있습니다 ...
문제를 해결하고 네트워크 오버 헤드를 줄이는 데 도움이되는 답변을 구현하여 Resolver를 NULL로 설정했습니다.
XmlReader r = ...r.XmlResolver = null; // prevent xsd or dtd parsing
다시 한 번 감사드립니다. Andy