通过HTTP

时间:2016-12-25 13:44:48

标签: c# rest wcf service

我在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 image description here

编辑:我注意到如果我在某个地方设置断点并运行,我会在&#34; WCF测试客户端&#34;中看到以下错误:弹出的窗口: &#34;错误:无法从http://localhost:59250/BookStoreImpl.svc获取元数据如果这是您有权访问的Windows(R)Communication Foundation服务,请检查您是否已在指定地址启用元数据发布。有关启用元数据发布的帮助,请参阅http://go.microsoft.com/fwlink/?LinkId=65455.WS-Metadata Exchange错误URI上的MSDN文档:http://localhost:59250/BookStoreImpl.svc元数据包含无法解析的引用:&#39; http://localhost:59250/BookStoreImpl.svc&#39;。所请求的服务,&#39; http://localhost:59250/BookStoreImpl.svc&#39;无法激活。有关详细信息,请参阅服务器的诊断跟踪日志.HTTP GET错误URI:http://localhost:59250/BookStoreImpl.svc下载&#39; http://localhost:59250/BookStoreImpl.svc&#39;时出错。请求失败并显示错误消息: - 没有协议绑定与给定地址匹配&#39; http://localhost:8080/bookservice/&#39;。协议绑定在IIS或WAS配置中的站点级别配置。 body {font-family:&#34; Verdana&#34 ;; font-weight:normal; font-size:.7em; color:black;} p {font-family:&#34; Verdana&#34 ;; font-重量:正常;颜色:黑色;边距顶部:-5px} b {font-family:&#34; Verdana&#34 ;; font-weight:bold;颜色:黑色; margin-top:-5px} H1 {font -family:&#34; Verdana&#34 ;; font-weight:normal; font-size:18pt; color:red} H2 {font-family:&#34; Verdana&#34 ;; font-weight:normal; font -size:14pt; color:maroon} pre {font-family:&#34; Consolas&#34;,&#34; Lucida Console&#34;,Monospace; font-size:11pt; margin:0; padding:0.5em ; line-height:14pt} .marker {font-weight:bold; color:black; text-decoration:none;} .version {color:grey;} .error {margin-bottom:10px;} .expandable {text-decoration:underline;字体重量:粗体;颜色:海军;光标:手; } @media screen and(max-width:639px){pre {width:440px;溢出:自动;白色空间:预包装;自动换行:break-word; @media screen和(max-width:479px){pre {width:280px; &#39; /&#39;中的

服务器错误应用程序。

没有协议绑定与给定地址匹配&#39; http://localhost:8080/bookservice/&#39;。协议绑定在IIS或WAS配置中的站点级别配置。

描述:在执行当前Web请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。

异常详细信息: System.InvalidOperationException:没有协议绑定与给定地址匹配&#39; http://localhost:8080/bookservice/&#39;。协议绑定在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.
< b>堆栈跟踪:

[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.SingletonChannelListener3.OnOpen(TimeSpan timeout) +78 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) '"SecurityNegotiationContract"' 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.Security.NegotiationTokenAuthenticator1.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.SecurityChannelListener1.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) '"IssueAndRenewSession"' 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.Security.SecuritySessionSecurityTokenAuthenticator.OnOpen(TimeSpan timeout) +129 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.SecuritySessionServerSettings.OnOpen(TimeSpan timeout) +759 System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen(TimeSpan timeout) +21 System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) +308 System.ServiceModel.Security.SecurityListenerSettingsLifetimeManager.Open(TimeSpan timeout) +130 System.ServiceModel.Channels.SecurityChannelListener1.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.DatagramChannelDemuxer2.OnOuterListenerOpen(ChannelDemuxerFilter filter, IChannelListener listener, TimeSpan timeout) at System.ServiceModel.Channels.SingletonChannelListener3.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.NegotiationTokenAuthenticator1.OnOpen(TimeSpan timeout) at System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen(TimeSpan timeout) at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) at System.ServiceModel.Security.CommunicationObjectSecurityTokenAuthenticator.Open(TimeSpan timeout) at System.ServiceModel.Security.SymmetricSecurityProtocolFactory.OnOpen(TimeSpan timeout) at System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen(TimeSpan timeout) at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) at System.ServiceModel.Security.SecurityListenerSettingsLifetimeManager.Open(TimeSpan timeout) at System.ServiceModel.Channels.SecurityChannelListener1.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) '"IssueAndRenewSession"' 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.SecuritySessionSecurityTokenAuthenticator.OnOpen(TimeSpan timeout) at System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen(TimeSpan timeout) at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) at System.ServiceModel.Security.CommunicationObjectSecurityTokenAuthenticator.Open(TimeSpan timeout) at System.ServiceModel.Security.SecuritySessionServerSettings.OnOpen(TimeSpan timeout) at System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen(TimeSpan timeout) at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) at System.ServiceModel.Security.SecurityListenerSettingsLifetimeManager.Open(TimeSpan timeout) at System.ServiceModel.Channels.SecurityChannelListener 1.OnOpen(TimeSpan超时)在System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan超时)处于System.ServiceModel.Dispatcher。 ChannelDispatcher.OnOpen(TimeSpan timeout)[InvalidOperationException]:&#39; http://localhost:8080/bookservice/&#39;的ChannelDispatcher与合同&#39;&#34; IBookStore&#34;&#39;无法打开其IChannelListener。处于System.ServiceModel.Channels.OnOpen(TimeSpan超时)的System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan超时),位于System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan超时),位于System.ServiceModel.Channels.CommunicationObject.Open处于System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen(TimeSpan timeout) (TimeSpan timeout)System.ServiceModel.ServiceHostingEnvironment.HostingManager.ActivateService(ServiceActivationInfo serviceActivationInfo,EventTraceActivity eventTraceActivity)System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath,EventTraceActivity eventTraceActivity)[ServiceActivationException]:service&#39; / BookStoreImpl .SVC&#39;由于编译期间的异常,无法激活。异常消息是:&#39; http://localhost:8080/bookservice/&#39;中的ChannelDispatcher与合同&#39;&#34; IBookStore&#34;&#39;无法在System.ServiceModel.Activation.ServiceHttpModul.EndProcessRequest(IAsyncResult ar)的System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult结果)的System.Runtime.AsyncResult.End [TAsyncResult](IAsyncResult结果)中打开其IChannelListener .. )在System.Web.HttpApplication.AsyncEventExecutionStep.OnAsyncEventCompletion(IAsyncResult ar) - &gt; - 。&#34;

2 个答案:

答案 0 :(得分:5)

好像是您的WCF托管问题。

WCF服务应该在某个主机内运行。它可以是控制台应用程序,ASP.NET应用程序,Windows服务等。

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

您很可能只是在Visual Studio中调试下启动应用程序。在这种情况下,您应该检查Project url是否配置正确。 打开项目属性,Web选项卡。项目网址&#39;中指定了哪个地址?编辑框?

enter image description here

默认情况下,VS放置&#39; localhost:一些随机端口&#39;,例如:http://localhost:38577/。在您的情况下,端口很可能是从错误中看到的59250

  

错误:无法从中获取元数据   http://localhost:59250/BookStoreImpl.svc

如果是这种情况,并且您想要坚持使用Web.config,请将此值更改为http://localhost:8080/bookservice/,然后按&#39;创建虚拟目录&#39;并重新启动调试会话。然后尝试再次访问GetBooksList方法。

答案 1 :(得分:1)

要查看基本绑定是否可以进行此更改。

<service behaviorConfiguration="MyServiceBehavior" name="BookStore.BookStoreImpl">
    <endpoint address="" 
              behaviorConfiguration="WebBehavior"
              binding="basicHttpBinding"
              bindingConfiguration="HttpBinding"    
              contract="BookStore.IBookStore">
    </endpoint>
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>