-1

客户App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.serviceModel>
        <bindings>
            <wsHttpBinding>
                <binding name="WSHttpBinding_INewsletterService">
                    <security mode="Message">
                        <message clientCredentialType="UserName" />
                    </security>
                </binding>
            </wsHttpBinding>
        </bindings>
        <client>
            <endpoint address="http://127.0.0.1:8001/NewsletterService.svc/username"
                      binding="wsHttpBinding"
                      bindingConfiguration="WSHttpBinding_INewsletterService"
                      behaviorConfiguration="ClientCertificateBehavior"
                      contract="NewsletterServiceReference.INewsletterService"
                      name="WSHttpBinding_INewsletterService">
              <identity>
                <dns value="Newsletter"/>
              </identity>
            </endpoint>
        </client>
      <behaviors>
        <endpointBehaviors>
          <behavior name="ClientCertificateBehavior">
            <clientCredentials>
              <serviceCertificate>
                <authentication certificateValidationMode="PeerOrChainTrust"/>
              </serviceCertificate>
            </clientCredentials>
          </behavior>
        </endpointBehaviors>
      </behaviors>

    </system.serviceModel>
</configuration>

主持人Web.config

<?xml version="1.0"?>
<configuration>
  <connectionStrings>
    <add name="NewsletterEntities" connectionString="metadata=res://*/NewsletterDAL_EF.csdl|res://*/NewsletterDAL_EF.ssdl|res://*/NewsletterDAL_EF.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=(local)\SQLEXPRESS;Initial Catalog=Newsletter;Integrated Security=True;Pooling=False;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient"/>
  </connectionStrings>
  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <system.serviceModel>
    <services>
      <service name="WCFHost.NewsletterService"
               behaviorConfiguration="NewsletterServiceBehavior">
        <endpoint address="username"
                  binding="wsHttpBinding"
                  contract="WCFHost.INewsletterService"
                  bindingConfiguration="Binding">
          <identity>
            <dns value="Newsletter"/>
          </identity>

        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8001/WcfServiceLibrary/service" />
          </baseAddresses>
        </host>
      </service>
    </services>
    <bindings>
      <wsHttpBinding>
        <binding name="Binding">
          <security mode="Message">
            <message clientCredentialType="UserName"/>
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
    <behaviors>
      <serviceBehaviors>
        <behavior name="NewsletterServiceBehavior">
          <serviceDebug includeExceptionDetailInFaults="true"/>
          <serviceCredentials>
            <userNameAuthentication userNamePasswordValidationMode="Custom"
                                    customUserNamePasswordValidatorType="WCFHost.CustomUserNameValidator, WCFHost"/>
            <serviceCertificate findValue="Newsletter" storeLocation="LocalMachine" storeName="TrustedPeople" x509FindType="FindBySubjectName"/>
          </serviceCredentials>
          <serviceMetadata httpGetEnabled="true"/>
        </behavior>
        <behavior>
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <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>

CustomUserNameValidator.cs

using System;
using System.IdentityModel.Selectors;
using System.ServiceModel;

namespace WCFHost
{
    public class CustomUserNameValidator : UserNamePasswordValidator
    {
        public override void Validate(string userName, string password)
        {
            if (null == userName || null == password)
            {
                throw new ArgumentNullException();
            }

            if (!(userName == "username" && password == "password"))
            {
                throw new FaultException("Unknown Username or Incorrect Password");
            }
        }
    }
}

MainWindow.xaml.cs

using Newsletter.Common;
using Newsletter.UI.NewsletterServiceReference;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;

namespace Newsletter.UI
{
    public partial class MainWindow : Window
    {
        private List<MessageDTO> _messages;
        private List<RecipientDTO> _recipients;
        private NewsletterServiceClient _client;

        public MainWindow()
        {
            InitializeComponent();
            _recipients = new List<RecipientDTO>();
            _client = new NewsletterServiceClient();
            _client.ClientCredentials.UserName.UserName = "username";
            _client.ClientCredentials.UserName.Password = "password";
        }

        [...]

        private async void MainWindowLoadedAsync(object sender, RoutedEventArgs e)
        {
            await _client.AddMailingListAsync("All Recipients"); //Exception here
        }

        [...]
}

我得到的例外:

System.ServiceModel.FaultException`1 was unhandled by user code
  HResult=-2146233087
  Message=The underlying provider failed on Open.
  Source=System.ServiceModel
  Action=http://schemas.microsoft.com/net/2005/12/windowscommunicationfoundation/dispatcher/fault
  StackTrace:
       at System.ServiceModel.Channels.ServiceChannel.ThrowIfFaultUnderstood(Message reply, MessageFault fault, String action, MessageVersion version, FaultConverter faultConverter)
       at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
       at System.ServiceModel.Channels.ServiceChannel.EndCall(String action, Object[] outs, IAsyncResult result)
       at System.ServiceModel.Channels.ServiceChannelProxy.TaskCreator.<>c__DisplayClass2.<CreateTask>b__1(IAsyncResult asyncResult)
       at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization)
    --- End of stack trace from previous location where exception was thrown ---
       at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
       at Newsletter.UI.MainWindow.<MainWindowLoadedAsync>d__0.MoveNext() in c:\Users\Pawel\Dropbox\VS12_projects\Newsletter_2_new\Newsletter.UI\MainWindow.xaml.cs:line 43
  InnerException: 

我究竟做错了什么?

更新:InnerException 消息:

Cannot open database "Newsletter" requested by the login. The login failed.
Login failed for user 'IIS APPPOOL\.NET v4.5'.
4

1 回答 1

0

为了解决这个问题,我必须将 IIS AppPool 设置为数据库所有者。

于 2013-01-14T16:52:24.463 回答