运行 WCF 服务获取错误无法添加服务。服务元数据可能无法访问
Run WCF service getting error Failed to add a service. Service metadata may not be accessible
我尝试了上传文件的 WCF 服务。
代码如下:
restService.svc
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.IO;
using System.ServiceModel.Web;
namespace restService
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "restService" in code, svc and config file together.
// NOTE: In order to launch WCF Test Client for testing this service, please select restService.svc or restService.svc.cs at the Solution Explorer and start debugging.
public class restService : IrestService
{
[WebInvoke(Method = "POST", UriTemplate = "UploadFile?fileName={fileName}")]
public string UploadFile(string fileName, Stream fileContents)
{
//save file
try
{
string absFileName = string.Format("{0}\FileUpload\{1}"
, AppDomain.CurrentDomain.BaseDirectory
, fileName);
using (FileStream fs = new FileStream(absFileName, FileMode.Create))
{
fileContents.CopyTo(fs);
fileContents.Close();
}
return "Upload OK";
}
catch (Exception ex)
{
return "FAIL ==> " + ex.Message;
}
}
}
}
IrestService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.IO;
namespace restService
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IrestService" in both code and config file together.
[ServiceContract]
public interface IrestService
{
[OperationContract]
string UploadFile(string fileName, Stream fileContents);
}
}
web.config
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation targetFramework="4.5" />
<httpRuntime targetFramework="4.5"/>
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<!--
To browse web app root directory during debugging, set the value below to true.
Set to false before deployment to avoid disclosing web app folder information.
-->
<directoryBrowse enabled="true"/>
</system.webServer>
</configuration>
当我使用 WCF 测试客户端测试服务时,出现错误:
Failed to add a service. Service metadata may not be accessible. Make
sure your service is running and exposing metadata.
Error: Cannot obtain Metadata from
http://localhost:49202/restService.svc If this is a Windows (R)
Communication Foundation service to which you have access, please
check that you have enabled metadata publishing at the specified
address. For help enabling metadata publishing, please refer to the
MSDN documentation at
http://go.microsoft.com/fwlink/?LinkId=65455.WS-Metadata Exchange
Error URI: http://localhost:49202/restService.svc Metadata contains a
reference that cannot be resolved:
'http://localhost:49202/restService.svc'. The requested service,
'http://localhost:49202/restService.svc' could not be activated. See
the server's diagnostic trace logs for more information.HTTP GET Error
URI: http://localhost:49202/restService.svc There was an error
downloading 'http://localhost:49202/restService.svc'. The request
failed with the error message:-- Server Error in '/' Application.
For request in operation UploadFile to be a stream the operation must
have a single parameter whose type is Stream. Description: An
unhandled exception occurred during the execution of the current web
request. Please review the stack trace for more information about the
error and where it originated in the code.
Exception Details: System.InvalidOperationException: For request in
operation UploadFile to be a stream the operation must have a single
parameter whose type is Stream.
Source Error:
An unhandled exception was generated during the execution of the
current web request. Information regarding the origin and location of
the exception can be identified using the exception stack trace below.
Stack Trace:
[InvalidOperationException: For request in operation UploadFile to be
a stream the operation must have a single parameter whose type is
Stream.]
System.ServiceModel.Dispatcher.StreamFormatter.ValidateAndGetStreamPart(MessageDescription
messageDescription, Boolean isRequest, String operationName) +12750641
System.ServiceModel.Dispatcher.OperationFormatter..ctor(OperationDescription
description, Boolean isRpc, Boolean isEncoded) +457
System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter..ctor(OperationDescription
description, DataContractFormatAttribute dataContractFormatAttribute,
DataContractSerializerOperationBehavior serializerFactory) +58
System.ServiceModel.Description.DataContractSerializerOperationBehavior.GetFormatter(OperationDescription
operation, Boolean& formatRequest, Boolean& formatReply, Boolean
isProxy) +217
System.ServiceModel.Description.DataContractSerializerOperationBehavior.System.ServiceModel.Description.IOperationBehavior.ApplyDispatchBehavior(OperationDescription
description, DispatchOperation dispatch) +58
System.ServiceModel.Description.DispatcherBuilder.BindOperations(ContractDescription
contract, ClientRuntime proxy, DispatchRuntime dispatch) +250
System.ServiceModel.Description.DispatcherBuilder.InitializeServiceHost(ServiceDescription
description, ServiceHostBase serviceHost) +3171
System.ServiceModel.ServiceHostBase.InitializeRuntime() +65
System.ServiceModel.ServiceHostBase.OnBeginOpen() +34
System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan timeout) +49
System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan
timeout) +308
System.ServiceModel.Channels.CommunicationObject.Open() +36
System.ServiceModel.HostingManager.ActivateService(ServiceActivationInfo
serviceActivationInfo, EventTraceActivity eventTraceActivity) +90
System.ServiceModel.HostingManager.EnsureServiceAvailable(String
normalizedVirtualPath, EventTraceActivity eventTraceActivity)
+598[ServiceActivationException: The service '/restService.svc' cannot be activated due to an exception during compilation. The exception
message is: For request in operation UploadFile to be a stream the
operation must have a single parameter whose type is Stream..]
System.Runtime.AsyncResult.End(IAsyncResult result) +485044
System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult
result) +174
System.ServiceModel.Activation.ServiceHttpHandler.EndProcessRequest(IAsyncResult
result) +6
System.Web.CallHandlerExecutionStep.OnAsyncHandlerCompletion(IAsyncResult
ar) +129
我想知道我的代码出了什么问题?
根据 MSDN https://msdn.microsoft.com/en-us/library/ms733742(v=vs.110).aspx
The programming model for streaming is straightforward. For receiving streamed data, specify an operation contract that has a single Stream typed input parameter. For returning streamed data, return a Stream reference.
流式传输时,您的方法中不能有其他参数。有一个额外的 fileName 参数导致异常。
您可以使用消息协定来完成相同的事情,并将附加字段作为 class 的属性传递,只要只有一个 属性 是 Stream。
[MessageContract]
public class UploadStreamMessage
{
[MessageHeader]
public string fileName;
[MessageBodyMember]
public Stream fileContents;
}
我尝试了上传文件的 WCF 服务。
代码如下:
restService.svc
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.IO;
using System.ServiceModel.Web;
namespace restService
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "restService" in code, svc and config file together.
// NOTE: In order to launch WCF Test Client for testing this service, please select restService.svc or restService.svc.cs at the Solution Explorer and start debugging.
public class restService : IrestService
{
[WebInvoke(Method = "POST", UriTemplate = "UploadFile?fileName={fileName}")]
public string UploadFile(string fileName, Stream fileContents)
{
//save file
try
{
string absFileName = string.Format("{0}\FileUpload\{1}"
, AppDomain.CurrentDomain.BaseDirectory
, fileName);
using (FileStream fs = new FileStream(absFileName, FileMode.Create))
{
fileContents.CopyTo(fs);
fileContents.Close();
}
return "Upload OK";
}
catch (Exception ex)
{
return "FAIL ==> " + ex.Message;
}
}
}
}
IrestService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.IO;
namespace restService
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IrestService" in both code and config file together.
[ServiceContract]
public interface IrestService
{
[OperationContract]
string UploadFile(string fileName, Stream fileContents);
}
}
web.config
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation targetFramework="4.5" />
<httpRuntime targetFramework="4.5"/>
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<!--
To browse web app root directory during debugging, set the value below to true.
Set to false before deployment to avoid disclosing web app folder information.
-->
<directoryBrowse enabled="true"/>
</system.webServer>
</configuration>
当我使用 WCF 测试客户端测试服务时,出现错误:
Failed to add a service. Service metadata may not be accessible. Make sure your service is running and exposing metadata.
Error: Cannot obtain Metadata from http://localhost:49202/restService.svc If this is a Windows (R) Communication Foundation service to which you have access, please check that you have enabled metadata publishing at the specified address. For help enabling metadata publishing, please refer to the MSDN documentation at http://go.microsoft.com/fwlink/?LinkId=65455.WS-Metadata Exchange Error URI: http://localhost:49202/restService.svc Metadata contains a reference that cannot be resolved: 'http://localhost:49202/restService.svc'. The requested service, 'http://localhost:49202/restService.svc' could not be activated. See the server's diagnostic trace logs for more information.HTTP GET Error URI: http://localhost:49202/restService.svc There was an error downloading 'http://localhost:49202/restService.svc'. The request failed with the error message:-- Server Error in '/' Application.
For request in operation UploadFile to be a stream the operation must have a single parameter whose type is Stream. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: For request in operation UploadFile to be a stream the operation must have a single parameter whose type is Stream.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[InvalidOperationException: For request in operation UploadFile to be a stream the operation must have a single parameter whose type is Stream.]
System.ServiceModel.Dispatcher.StreamFormatter.ValidateAndGetStreamPart(MessageDescription messageDescription, Boolean isRequest, String operationName) +12750641 System.ServiceModel.Dispatcher.OperationFormatter..ctor(OperationDescription description, Boolean isRpc, Boolean isEncoded) +457
System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter..ctor(OperationDescription description, DataContractFormatAttribute dataContractFormatAttribute, DataContractSerializerOperationBehavior serializerFactory) +58
System.ServiceModel.Description.DataContractSerializerOperationBehavior.GetFormatter(OperationDescription operation, Boolean& formatRequest, Boolean& formatReply, Boolean isProxy) +217
System.ServiceModel.Description.DataContractSerializerOperationBehavior.System.ServiceModel.Description.IOperationBehavior.ApplyDispatchBehavior(OperationDescription description, DispatchOperation dispatch) +58
System.ServiceModel.Description.DispatcherBuilder.BindOperations(ContractDescription contract, ClientRuntime proxy, DispatchRuntime dispatch) +250
System.ServiceModel.Description.DispatcherBuilder.InitializeServiceHost(ServiceDescription description, ServiceHostBase serviceHost) +3171
System.ServiceModel.ServiceHostBase.InitializeRuntime() +65
System.ServiceModel.ServiceHostBase.OnBeginOpen() +34
System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan timeout) +49
System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) +308
System.ServiceModel.Channels.CommunicationObject.Open() +36
System.ServiceModel.HostingManager.ActivateService(ServiceActivationInfo serviceActivationInfo, EventTraceActivity eventTraceActivity) +90
System.ServiceModel.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath, EventTraceActivity eventTraceActivity) +598[ServiceActivationException: The service '/restService.svc' cannot be activated due to an exception during compilation. The exception message is: For request in operation UploadFile to be a stream the operation must have a single parameter whose type is Stream..]
System.Runtime.AsyncResult.End(IAsyncResult result) +485044
System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result) +174
System.ServiceModel.Activation.ServiceHttpHandler.EndProcessRequest(IAsyncResult result) +6
System.Web.CallHandlerExecutionStep.OnAsyncHandlerCompletion(IAsyncResult ar) +129
我想知道我的代码出了什么问题?
根据 MSDN https://msdn.microsoft.com/en-us/library/ms733742(v=vs.110).aspx
The programming model for streaming is straightforward. For receiving streamed data, specify an operation contract that has a single Stream typed input parameter. For returning streamed data, return a Stream reference.
流式传输时,您的方法中不能有其他参数。有一个额外的 fileName 参数导致异常。
您可以使用消息协定来完成相同的事情,并将附加字段作为 class 的属性传递,只要只有一个 属性 是 Stream。
[MessageContract]
public class UploadStreamMessage
{
[MessageHeader]
public string fileName;
[MessageBodyMember]
public Stream fileContents;
}