当我调用http://localhost/TestService.svc/GetColors时,我收到一个 Http (400) 错误请求。当我在提琴手中运行它时,我也会收到错误的请求。当我通过 wcf 测试客户端调用服务时,它工作正常。什么可能导致这种情况?
服务合约:
[ServiceContract]
public interface ITestService
{
[OperationContract]
string GetColors();
}
ITestService 的实现:
[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
public class TestService : ITestService
{
public List<Color> GetColors()
{
List<Color> colors= new List<Color>();
colors.Add(new Color { Name = "Red", Code = "123" });
colors.Add(new Color { Name = "Blue", Code = "323" });
colors.Add(new Color { Name = "Green", Code = "3394" });
return colors;
}
}
这是我的 web.config:
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
</system.web>
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="CustomAuthentication">
<security mode="Message">
<message clientCredentialType="UserName"/>
</security>
</binding>
</wsHttpBinding>
</bindings>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
<services>
<service name="TestService.TestService"
behaviorConfiguration="CustomValidator" >
<endpoint
address=""
binding="wsHttpBinding"
bindingConfiguration="CustomAuthentication"
contract="TestService.ITestService">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint
address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="http://localhost/TestService/" />
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="CustomValidator">
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom"
customUserNamePasswordValidatorType="TestService.CustomUserNameValidator, TestService"/>
<serviceCertificate findValue="Test" storeLocation="LocalMachine"
storeName="My" x509FindType="FindBySubjectName"/>
</serviceCredentials>
<serviceMetadata httpGetEnabled="True"/>
</behavior>
<behavior>
<serviceMetadata httpGetEnabled="True"/>
<serviceDebug includeExceptionDetailInFaults="False"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
当我调用它时,我只需打开任何浏览器并输入 url http://localhost/TestService.svc/GetColors
。如果我通过开发环境执行此操作,我会看到 Http 400 bad request。如果我通过 IIS 执行此操作,我只会看到一个空白页。
这是内部异常:
<ExceptionString>System.Xml.XmlException: The body of the message cannot be read
because it is empty.</ExceptionString>
关于我的 CustomUserNameValidation 的另一个问题:
我正在通过 UserNamePasswordValidator 的 Validate 方法实现自定义验证,但是当我通过 wcf 客户端调用 GetColors 之类的东西时,它不会调用 Validate 方法。我可以让它调用验证的唯一方法是直接在 GetColors 中调用 Validate(user,pass)。我认为如果您在 web.config 中正确设置了它,那么每次服务调用都会自动调用它。