.net 调用 WCF 服务操作时出现 HTTP 400 错误请求?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5995425/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 15:34:36  来源:igfitidea点击:

HTTP 400 Bad Request when calling WCF Service Operation?

.netwcfbad-request

提问by Xaisoft

When I call http://localhost/TestService.svc/GetColors, I get a Http (400) Bad Request. When I run this in fiddler, I also get Bad Request. When I invoke the service through the wcf test client, it works fine though. What could cause this?

当我调用http://localhost/TestService.svc/GetColors 时,我收到一个 Http (400) 错误请求。当我在 fiddler 中运行它时,我也会收到错误的请求。当我通过 wcf 测试客户端调用服务时,它工作正常。什么可能导致这种情况?

Service contract:

服务合约:

[ServiceContract]
public interface ITestService
{
    [OperationContract]
    string GetColors();
}

Implementation of ITestService:

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;
    }
}

Here is my web.config:

这是我的 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>

When I call it, I just open up a any browser and put the url http://localhost/TestService.svc/GetColors. If I do it through the dev environment, I see the Http 400 bad request. If I do it through IIS, I just see a blank page.

当我调用它时,我只需打开任何浏览器并输入 url http://localhost/TestService.svc/GetColors。如果我通过开发环境执行此操作,则会看到 Http 400 错误请求。如果我通过 IIS 执行此操作,我只会看到一个空白页面。

Here is the InnerException:

这是内部异常:

<ExceptionString>System.Xml.XmlException: The body of the message cannot be read  
because it is empty.</ExceptionString>

Another question regarding my CustomUserNameValidation:

关于我的 CustomUserNameValidation 的另一个问题:

I am implementing Custom Validation through the Validate Method of UserNamePasswordValidator, but when I call something like GetColors through the wcf client, it does not invoke the Validate method. The only way I can get it to Invoke validate is if I call Validate(user,pass) directly in GetColors. I thought it woulld be called automatically for every service call if you have it setup correctly in web.config.

我正在通过 UserNamePasswordValidator 的 Validate 方法实现自定义验证,但是当我通过 wcf 客户端调用 GetColors 之类的东西时,它不会调用 Validate 方法。我可以让它调用验证的唯一方法是,如果我直接在 GetColors 中调用 Validate(user,pass)。我认为如果您在 web.config 中正确设置了它,它将为每个服务调用自动调用。

采纳答案by marc_s

Your service contract and service implementation don't seem to match....

您的服务合同和服务实施似乎不匹配....

The service contract defines a single stringto be returned from GetColors():

服务合同定义了一个string从 返回的单曲GetColors()

[ServiceContract]
public interface ITestService
{
    [OperationContract]
    string GetColors();
}

But the implementation returns a List<Color>instead:

但是实现返回一个List<Color>

[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
public class TestService : ITestService
{
    public List<Color> GetColors()
    {

Is there any chance you changed your service implementation, and forgot to update the service contract??

有没有可能你改变了你的服务实现,忘记更新服务合同?

Also: since this is a SOAP service with a wsHttpBinding, you cannotjust call the method from a browser by browsing to its address - you need to use the WCF Test Client (which works, as you say). Nor can you just call it from Fiddler, either - you would have to manually create the entire SOAP envelope with header and body and all - not an easy task at all.

另外:由于这是一个带有 的 SOAP 服务wsHttpBinding,您不能仅通过浏览到其地址来从浏览器调用该方法 - 您需要使用 WCF 测试客户端(如您所说,它可以工作)。您也不能仅仅从 Fiddler 调用它——您必须手动创建整个 SOAP 信封,包括标题和正文以及所有内容——这根本不是一件容易的事。

What you can try is to go to http://localhost/TestService.svc?wsdlto check whether you'll get back the proper WSDL for the service.

您可以尝试去http://localhost/TestService.svc?wsdl检查您是否会为该服务取回正确的 WSDL。

回答by Simon Mourier

Many things could cause this. I suggest you first enable WCF Tracing, it's usually very helpful as it gives you the server side output of what's really going on. Here is a link that should help: How to enable WCF tracing

很多事情都可能导致这种情况。我建议您首先启用 WCF 跟踪,它通常非常有用,因为它可以为您提供真实情况的服务器端输出。这是一个应该有帮助的链接:如何启用 WCF 跟踪

EDIT: One little thing to note with WCF: unlike auto generated ole' ASMX web service it does not allow you to browseto the base address with a standard browser. You can browse to the Metadata address (the mex one), but not to the root. This is just by design (the HTTP method is not supported I believe).

编辑:一个小一点要注意与WCF:不同于自动生成的OLE” ASMX Web服务不会允许你浏览到的基地址与一个标准的浏览器。您可以浏览到元数据地址(mex 地址),但不能浏览到根。这只是设计使然(我相信不支持 HTTP 方法)。