【发布时间】:2018-03-13 17:31:28
【问题描述】:
我们有一个用 .NET Standard 2.0 编译的库,它有一个 WCF 服务。为了向 Web 服务的请求添加自定义标头,我们在此处实现了代码:https://blogs.msdn.microsoft.com/mohamedg/2012/12/13/adding-http-headers-to-wcf-calls/
当我们在 .NET Framework 应用程序中引用这个库时,我们可以对我们想要的 Web 服务进行任何调用,并且返回正确的结果就好了。但是,在 .NET Core 2.0 应用程序中,库经常(但不总是!)抛出 System.FormatException,具体取决于我们设置的用户代理。
“Mozilla/4.0”之类的内容不会引发错误,但“Mozilla/4.0(兼容;MSIE 6.0;MS Web 服务客户端协议 4.0.30319.42000)”会,但仅限于带有错误消息“值的格式(兼容;MSIE 6.0;MS Web 服务客户端协议 4.0.30319.42000)'的核心应用程序无效。”。
简而言之,这里是代码(从没有实现的接口中省略了方法)。当前的用户代理是硬编码的,只是为了排除故障。
internal class ClientUserAgentMessage : IClientMessageInspector
{
public ClientUserAgentMessage(string userAgent) { }
public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
HttpRequestMessageProperty property = new HttpRequestMessageProperty();
//This is an example user agent that fails, and we would not expect it to.
property.Headers["User-Agent"] = "Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 4.0.30319.42000)";
request.Properties.Add(HttpRequestMessageProperty.Name, property);
return null;
}
}
internal class UserAgentEndpointBehavior : IEndpointBehavior
{
public UserAgentEndpointBehavior() { }
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
clientRuntime.ClientMessageInspectors.Add(new ClientUserAgentMessage());
}
}
上面的代码是在一个引用标准 dll 的应用程序中实现的(省略客户端初始化细节):
//SoapClient and related WCF code is generated from the web service via svcutil.exe
SoapClient client = new SoapClient(...);
client.Endpoint.EndpointBehaviors.Add(new UserAgentEndpointBehavior());
//Call some web service functions...
//This succeeds in a .NET 4.7 app,
//but blows up in a .NET Core 2.0 app due to the user agent being an "invalid format".
//client.Login();
当用户代理实际上似乎是一种有效格式时,为什么这只是 .NET Core 的问题?它似乎抱怨哪里有更多的 1 /,括号,冒号,分号,空格......基本上除了第一个 /,下划线和小数之外的任何非字母数字。
根据要求,完整的堆栈跟踪:
at System.Net.Http.Headers.HttpHeaderParser.ParseValue(String value, Object storeValue, Int32& index)
at System.Net.Http.Headers.ProductInfoHeaderValue.Parse(String input)
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpClientRequestChannel.HttpClientChannelAsyncRequest.PrepareMessageHeaders(Message message)
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpClientRequestChannel.HttpClientChannelAsyncRequest.<SendRequestAsync>d__13.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.ServiceModel.Channels.RequestChannel.<RequestAsync>d__33.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.ServiceModel.Channels.RequestChannel.<RequestAsyncInternal>d__32.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.TaskHelpers.WaitForCompletionNoSpin[TResult](Task`1 task)
at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(MethodCall methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(MethodInfo targetMethod, Object[] args)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Reflection.DispatchProxyGenerator.Invoke(Object[] args)
at generatedProxy_1.Login(LoginRequest )
at MyServiceNamespace.SoapClient.ServiceNamespace.Soap.Login(LoginRequest request)
at MyServiceNamespace.SoapClient.Login(String strUser, String strPass, String strKey)
at MyLibraryNamespace.MyClass.Login(String sUser, String sPass, String sKey)
FWIW,您可以设置为“User-Agent”以外的标题,一切都很好(或者至少,我尝试使用“XTESTX”,没有例外)。
【问题讨论】:
-
您将用户代理中的空格替换为
+。为什么? it isn't valid -
@Amy - 抱歉,必须在实验中期粘贴代码。请参阅更新的代码。相同的错误(略有不同的消息,第一个空格被打破之前的部分)无论是空格还是加号。
-
它可能有助于知道它到底在哪里爆炸(如堆栈跟踪)。 WCF 是核心堆栈的一个相当新的补充;这很可能是一个错误。
-
是的,这绝对是一个错误。具体来说,
PrepareMessageHeaders不应该使用ProductInfoHeaderValue.Parse来解析User-Agent值,因为该类只处理部分——完整的User-Agent标头是这些值的集合,如HttpRequestHeaders.UserAgent所示。总的来说,这些类的设计相当糟糕(我可以看到没有用于解析完整值的公共 API);我不怪核心作者弄错了。 -
我相信通过将 this line 从
_httpRequestMessage.Headers.UserAgent.Add(ProductInfoHeaderValue.Parse(value));更改为_httpRequestMessage.Headers.UserAgent.TryParseAdd(value);可以解决此问题,但我没有足够的动力完成整个测试/拉取请求。