gpt4 book ai didi

c# - 通过HTTP访问WCF服务

转载 作者:行者123 更新时间:2023-12-01 23:14:01 26 4
gpt4 key购买 nike

我在Visual Studio中编写了一个非常简单的WCF项目:

iBookStore:

using System.Collections.Generic;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;

namespace BookStore
{
[ServiceContract]
public interface IBookStore
{
[OperationContract]
[WebGet]
List<Book> GetBooksList();

[OperationContract]
[WebGet(UriTemplate = "GetBook/{id}")] // The value of UriTemplate defines the name that the
// client should use to turn to the function
Book GetBookById(int id);

[OperationContract]
[WebInvoke(UriTemplate = "AddBook/{name}", Method = "PUT")]
void AddBook(string name);

[OperationContract]
[WebInvoke(UriTemplate = "UpdateBook/{id}/{name}", Method = "POST")]
void UpdateBook(int id, string name);

[OperationContract]
[WebInvoke(UriTemplate = "DeleteBook/{id}", Method = "DELETE")]
void DeleteBook(int id);
}


[DataContract]
public class Book
{
int id;
string name;


[DataMember]
public int ID
{
get { return id; }
set { id = value; }
}

[DataMember]
public string Name
{
get { return name; }
set { name = value; }
}
}
}

BookStoreImpl:
using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Activation;

namespace BookStore
{
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class BookStoreImpl : IBookStore
{
public void AddBook(string name)
{
using (var db = new BookStoreContext())
{
Book book = new BookStore.Book { Name = name };
db.Books.Add(book);
db.SaveChanges();
}
}

public void DeleteBook(int id)
{
try
{
using (var db = new BookStoreContext())
{
Book book = db.Books.Find(id);
db.Books.Remove(book);
db.SaveChanges();
}
}
catch
{
throw new FaultException("Something went wrong");
}
}

public Book GetBookById(int id)
{
using (var db = new BookStoreContext())
{
return db.Books.Find(id);
}
}

public List<Book> GetBooksList()
{
List<Book> allBooks = new List<Book>();
try
{
using (var db = new BookStoreContext())
{
IEnumerator<Book> booksEnum = db.Books.GetEnumerator();
booksEnum.Reset();
while (booksEnum.MoveNext())
{
allBooks.Add(booksEnum.Current);
}
}
}
catch
{
throw new FaultException("Something went wrong");
}
return allBooks;
}

public void UpdateBook(int id, string name)
{
try
{
using (var db = new BookStoreContext())
{
Book book = db.Books.Find(id);
book.Name = name;
db.SaveChanges();
}
}
catch
{
throw new FaultException("Something went wrong");
}
}
}
}

我的WebConfig文件是:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" />
<httpModules>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
</httpModules>
</system.web>

<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="MyServiceBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="WebBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="MyServiceBehavior" name="BookStore.BookStoreImpl">
<endpoint address="http://localhost:8080/bookservice/" binding="wsHttpBinding" contract="BookStore.IBookStore" />
<endpoint address="" behaviorConfiguration="WebBehavior"
binding="webHttpBinding"
contract="BookStore.IBookStore">
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
</system.serviceModel>
<!--
<system.serviceModel>
<services>
<service name="BookStore.BookStoreImpl">
<endpoint address="http://localhost:8080/bookservice"
behaviorConfiguration="restfulBehavior" binding="webHttpBinding"
bindingConfiguration="" contract="BookStore.IBookStore"
/>
<host>
<baseAddresses>
<add baseAddress="http://localhost:8080/bookservice" />
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="restfulBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
-->
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<remove name="ApplicationInsightsWebTracking" />
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
</modules>
<!--
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" />
<validation validateIntegratedModeConfiguration="false" />
</system.webServer>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>

我还创建了数据库,并使用.mdf文件将其附加到项目中,编译并运行该项目,运行该项目后,我可以在屏幕的右上角看到计时器正在运行。然后打开浏览器,在地址栏中输入: http://localhost:8080/bookservice/GetBooksList并按Enter键,然后显示错误页面。看起来我的请求一开始就没有到达服务器。谁能帮我了解原因?

这是错误:
enter image description here

编辑:我注意到,如果我在某个地方设置断点并运行,我会在弹出的“WCF测试客户端”窗口中看到以下错误:
“错误:无法从 http://localhost:59250/BookStoreImpl.svc获取元数据。如果这是您有权访问的Windows(R)Communication Foundation服务,请检查是否已在指定的地址启用了元数据发布。有关启用元数据发布的帮助,请参阅MSDN文档在 http://go.microsoft.com/fwlink/?LinkId=65455.WS-Metadata交换错误URI: http://localhost:59250/BookStoreImpl.svc元数据包含无法解析的引用:' http://localhost:59250/BookStoreImpl.svc'无法激活所请求的服务' http://localhost:59250/BookStoreImpl.svc'。有关更多信息,请参见服务器的诊断跟踪日志。HTTP GET错误URI: http://localhost:59250/BookStoreImpl.svc下载' http://localhost:59250/BookStoreImpl.svc'时出错。请求失败,并显示错误消息:-没有协议(protocol)绑定(bind)与给定的地址' http://localhost:8080/bookservice/'相匹配。协议(protocol)绑定(bind)是在IIS或WAS配置中的站点级别配置的。 “; font-weight:normal; font-size:.7em; color:black;} p {font-family:” Verdana“; font-weight:normal; color:black; margin-top:-5px} b {font -F amily:“Verdana”;字体粗细:粗体;颜色:黑色;边距:-5px} H1 {font-family:“Verdana”;字体粗细:normal;字体大小:18pt;颜色:红色} H2 {font-family:“Verdana”; font-weight:normal; font-size:14pt; color:maroon} pre {font-family:“Consolas”,“Lucida Console”,Monospace; font-size:11pt; margin: 0; padding:0.5em; line-height:14pt} .marker {font-weight:bold;颜色:黑色;文本装饰:无;} .version {颜色:灰色;}。错误{边距:10像素;} .expandable {文本装饰:下划线; font-weight:bold;颜色:海军蓝;光标:手; } @media屏幕和(最大宽度:639像素){前置{宽度:440像素;溢出:自动;空白:预包装;自动换行:断词; }} @media屏幕和(max-width:479px){pre {width:280px; '/'应用程序中的服务器错误。没有协议(protocol)绑定(bind)与给定地址“ http://localhost:8080/bookservice/”匹配。协议(protocol)绑定(bind)是在IIS或WAS配置中的站点级别配置的。说明:执行当前Web请求期间发生未处理的异常。请查看堆栈跟踪,以获取有关错误及其在代码中起源的更多信息。异常详细信息:System.InvalidOperationException:没有协议(protocol)绑定(bind)与给定地址 http://localhost:8080/bookservice/匹配。协议(protocol)绑定(bind)是在IIS或WAS配置中的站点级别配置的。源错误: 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.堆栈跟踪: [InvalidOperationException: No protocol binding matches the given address 'http://localhost:8080/bookservice/'. Protocol bindings are configured at the Site level in IIS or WAS configuration.] System.ServiceModel.Activation.HostedAspNetEnvironment.GetBaseUri(String transportScheme, Uri listenUri) +109963 System.ServiceModel.Channels.TransportChannelListener.OnOpening() +13058405 System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) +265 System.ServiceModel.Channels.DatagramChannelDemuxer2.OnOuterListenerOpen(ChannelDemuxerFilter filter, IChannelListener listener, TimeSpan timeout) +445 System.ServiceModel.Channels.SingletonChannelListener 3.OnOpen(TimeSpan超时)+78 System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan超时)+308 System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen(TimeSpan超时)+61 [InvalidOperationException:契约(Contract)为““SecurityNegotiationContract”“的'http://localhost:8080/bookservice/'处的ChannelDispatcher无法打开其IChannelListener。] System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen(TimeSpan超时)+134 System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan超时)+308 System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan超时)+136 System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan超时)+308 System.ServiceModel.Security.NegotiationTokenAuthenticator 1.OnOpen(TimeSpan timeout) +137 System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen(TimeSpan timeout) +21 System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) +308 System.ServiceModel.Security.CommunicationObjectSecurityTokenAuthenticator.Open(TimeSpan timeout) +23 System.ServiceModel.Security.SymmetricSecurityProtocolFactory.OnOpen(TimeSpan timeout) +513 System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen(TimeSpan timeout) +21 System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) +308 System.ServiceModel.Security.SecurityListenerSettingsLifetimeManager.Open(TimeSpan timeout) +86 System.ServiceModel.Channels.SecurityChannelListener 1.OnOpen(TimeSpan超时) +240 System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan超时)+308 System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen(TimeSpan超时)+61 [InvalidOperationException:位于'http://localhost:8080/bookservice/'处的ChannelDispatcher与契约(Contract)为'“IssueAndRenewSession” '无法打开其IChannelListener。] System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen(TimeSpan超时)+134 System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan超时)+308 System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan超时) +136 System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan超时)+308 System.ServiceModel.Security.SecuritySessionSecurityTokenAuthenticator.OnOpen(TimeSpan超时)+129 System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen(TimeSpan超时)+21 System.ServiceModel .Channels.CommunicationObject.Open(TimeSpan超时)+308 System.ServiceModel.Security.CommunicationObjectSecurityTokenAuthenticator.Open(TimeSpan超时)+23 System.ServiceModel.Security.SecuritySessionServerSettings.OnOpen(TimeSpan超时)+759 System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen(TimeSpan超时)+21 System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan超时)+308 System.ServiceModel.Security .SecurityListenerSettingsLifetimeManager.Open(TimeSpan超时)+130 System.ServiceModel.Channels.SecurityChannelListener 1.OnOpen(TimeSpan timeout) +240 System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) +308 System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen(TimeSpan timeout) +61[InvalidOperationException: The ChannelDispatcher at 'http://localhost:8080/bookservice/' with contract(s) '"IBookStore"' is unable to open its IChannelListener.] System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen(TimeSpan timeout) +134 System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) +308 System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan timeout) +136 System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) +308 System.ServiceModel.HostingManager.ActivateService(ServiceActivationInfo serviceActivationInfo, EventTraceActivity eventTraceActivity) +110 System.ServiceModel.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath, EventTraceActivity eventTraceActivity) +641[ServiceActivationException: The service '/BookStoreImpl.svc' cannot be activated due to an exception during compilation. The exception message is: The ChannelDispatcher at 'http://localhost:8080/bookservice/' with contract(s) '"IBookStore"' is unable to open its IChannelListener..] System.Runtime.AsyncResult.End(IAsyncResult result) +481507 System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result) +174 System.ServiceModel.Activation.ServiceHttpModule.EndProcessRequest(IAsyncResult ar) +351314 System.Web.AsyncEventExecutionStep.OnAsyncEventCompletion(IAsyncResult ar) +9791593</pre></code> </td> </tr> </table> <br> <hr width=100% size=1 color=silver> <b>Version Information:</b>ÿMicrosoft .NET Framework Version:4.0.30319; ASP.NET Version:4.6.1586.0 </font> </body></html><!-- [InvalidOperationException]: No protocol binding matches the given address 'http://localhost:8080/bookservice/'. Protocol bindings are configured at the Site level in IIS or WAS configuration. at System.ServiceModel.Activation.HostedAspNetEnvironment.GetBaseUri(String transportScheme, Uri listenUri) at System.ServiceModel.Channels.TransportChannelListener.OnOpening() at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) at System.ServiceModel.Channels.DatagramChannelDemuxer 2.OnOuterListenerOpen(System.ServiceModel.Channels.SingletonChannelListener 3.OnOpen(TimeSpan timeout) at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) at System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen(TimeSpan timeout)[InvalidOperationException]: The ChannelDispatcher at 'http://localhost:8080/bookservice/' with contract(s) '"SecurityNegotiationContract"' is unable to open its IChannelListener. at System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen(TimeSpan timeout) at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) at System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan timeout) at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) at System.ServiceModel.Security.NegotiationTokenAuthenticator 1。 System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan超时)在System.ServiceModel.Security.CommunicationObjectSecurityTokenAuthenticator.Open(TimeSpan超时)在System.ServiceModel.Security.SymmetricSecurityProtocolFactory.OnOpen( System.Ser的TimeSpan超时)在System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan超时)在System.ServiceModel.Security.Security.SecurityListenerSettingsLifetimeManager.Open(TimeSpan超时)在System.ServiceModel.Channels.SecurityChannelListener1.OnOpen()上的ViceModel.Security.WrapperSecurityCommunicationObject.OnOpen(TimeSpan超时) System.ServiceModel.Channels.CommunicationObject.Open处的TimeSpan超时)(System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen处的TimeSpan超时)[InvalidOperationException]:位于http://localhost:8080/bookservice/的ChannelDispatcher契约(Contract)为““IssueAndRenewSession”“的契约(Contract)无法打开其IChannelListener。在System.ServiceModel.Channels.CommunicationObject.Open(在System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan超时)在System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan超时)在System.ServiceModel.Channels.CommunicationObject.Open (System.ServiceModel.Security.SecuritySessionSecurityTokenAuthenticator.OnOpen(TimeSpan超时)处的System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen(System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan超时)处的(TimeSpan超时) System.ServiceModel.Security.Security.SecuritySessionServerSettings.OnOpen(TimeSpan超时)处的System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen(System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan超时)处的.Security.CommunicationObjectSecurityTokenAuthenticator.Open(TimeSpan超时)超时),位于System.ServiceModel.Security.SecurityListenerSettingsLifetimeMa Nager.Open(TimeSpan超时)在System.ServiceModel.Channels.SecurityChannelListener1.OnOpen(TimeSpan超时)在System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan超时)在System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen(TimeSpan超时)[ InvalidOperationException]:位于'http://localhost:8080/bookservice/'且契约(Contract)为'“IBookStore”'的ChannelDispatcher无法打开其IChannelListener。在System.ServiceModel.Channels.CommunicationObject.Open(在System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan超时)在System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan超时)在System.ServiceModel.Channels.CommunicationObject.Open (System.ServiceModel.ServiceHostingEnvironment.HostingManager.ActivateService(ServiceActivationInfo serviceActivationInfo,EventTraceActivity eventTraceActivity)在System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath,EventTraceActivity eventTraceActivity)上的(TimeSpan超时)由于编译期间发生异常而无法激活。异常消息是:契约(Contract)为“IBookStore”的“http://localhost:8080/bookservice/”处的ChannelDispatcher无法在System.ServiceModel.Activation处的System.Runtime.AsyncResult.End [TAsyncResult](IAsyncResult)处打开其IChannelListener。 “。位于System.Web.HttpApplication.AsyncEventExecutionStep.OnAsyncEventCompletion(IAsyncResult ar)处System.ServiceModel.Activation.ServiceHttpModule.EndProcessRequest(IAsyncResult ar)处的HostedHttpRequestAsyncResult.End(IAsyncResult结果)->-。”

最佳答案

好像是WCF托管问题。

WCF服务应在某些主机中运行。它可能是控制台应用程序,ASP.NET应用程序,Windows服务等。

在尝试访问url http://localhost:8080/bookservice/之前,是否已将服务部署为具有指定地址的IIS应用程序?

您很可能只是在Visual Studio中的调试下启动应用程序。在这种情况下,您应该检查是否正确配置了项目URL。
打开“项目”属性的“Web”选项卡。在“项目网址”编辑框中指定了什么地址?

enter image description here

默认情况下,VS将'localhost:some random port'放置在此处,例如:http://localhost:38577/。在您的情况下,从错误中可以看到该端口最有可能是59250

Error: Cannot obtain Metadata from http://localhost:59250/BookStoreImpl.svc



如果是这种情况,并且您希望坚持使用Web.config,则将此值更改为 http://localhost:8080/bookservice/,按“创建虚拟目录”,然后重新启动调试 session 。然后尝试再次访问 GetBooksList方法。

关于c# - 通过HTTP访问WCF服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41321612/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com