关于c#:WCF服务将不会返回500 Internal Server Error。相反,只有400错误请求

WCF service will not return 500 Internal Server Error. Instead, only 400 Bad Request

我已经创建了一个简单的RESTful WCF文件流服务。发生错误时,我希望生成一个500 Interal Server Error响应代码。而是,仅生成400个错误请求。
当请求有效时,我会收到正确的响应(200 OK),但是即使抛出异常,我也会得到400。

IFileService:

1
2
3
4
5
6
7
8
9
10
[ServiceContract]
public interface IFileService
{
    [OperationContract]
    [WebInvoke(Method ="GET",
        BodyStyle = WebMessageBodyStyle.Bare,
        ResponseFormat = WebMessageFormat.Json,
        UriTemplate ="/DownloadConfig")]
    Stream Download();
}

FileService:

1
2
3
4
5
6
7
8
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class GCConfigFileService : IGCConfigFileService
{
    public Stream Download()
    {
        throw new Exception();
    }
}

Web.Config

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<location path="FileService.svc">
<system.web>
 
   
  </authorization>
</system.web>
</location>
<system.serviceModel>
<client />
<behaviors>
  <serviceBehaviors>
    <behavior name="FileServiceBehavior">
      <serviceMetadata httpGetEnabled="true"/>
      <serviceDebug includeExceptionDetailInFaults="false" />
    </behavior>
  </serviceBehaviors>
  <endpointBehaviors>
    <behavior name="web">
      <webHttp/>
    </behavior>
  </endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
  multipleSiteBindingsEnabled="true" />
<services>
  <service name="FileService"
           behaviorConfiguration="FileServiceBehavior">
    <endpoint address=""
              binding="webHttpBinding"
              bindingConfiguration="FileServiceBinding"
              behaviorConfiguration="web"
              contract="IFileService"></endpoint>
  </service>
</services>
<bindings>
  <webHttpBinding>
    <binding
      name="FileServiceBinding"
      maxBufferSize="2147483647"
      maxReceivedMessageSize="2147483647"
      transferMode="Streamed"
      openTimeout="04:01:00"
      receiveTimeout="04:10:00"
      sendTimeout="04:01:00">
      <readerQuotas maxDepth="2147483647"
                    maxStringContentLength="2147483647"
                    maxArrayLength="2147483647"
                    maxBytesPerRead="2147483647"
                    maxNameTableCharCount="2147483647" />
    </binding>
  </webHttpBinding>
</bindings>


简单的:

尝试throw new WebFaultException(HttpStatusCode.InternalServerError);

要指定错误详细信息:

1
throw new WebFaultException<string>("Custom Error Message!", HttpStatusCode.InternalServerError);

先进的:

如果要通过为每个异常定义HTTP状态来更好地处理异常,则需要创建一个自定义ErrorHandler类,例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class HttpErrorHandler : IErrorHandler
{
   public bool HandleError(Exception error)
   {
      return false;
   }

   public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
   {
      if (fault != null)
      {
         HttpResponseMessageProperty properties = new HttpResponseMessageProperty();
         properties.StatusCode = HttpStatusCode.InternalServerError;
         fault.Properties.Add(HttpResponseMessageProperty.Name, properties);
      }
   }
}

然后,您需要创建服务行为以附加到您的服务:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class ErrorBehaviorAttribute : Attribute, IServiceBehavior
{
   Type errorHandlerType;

   public ErrorBehaviorAttribute(Type errorHandlerType)
   {
      this.errorHandlerType = errorHandlerType;
   }

   public void Validate(ServiceDescription description, ServiceHostBase serviceHostBase)
   {
   }

   public void AddBindingParameters(ServiceDescription description, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection parameters)
   {
   }

   public void ApplyDispatchBehavior(ServiceDescription description, ServiceHostBase serviceHostBase)
   {
      IErrorHandler errorHandler;

      errorHandler = (IErrorHandler)Activator.CreateInstance(errorHandlerType);
      foreach (ChannelDispatcherBase channelDispatcherBase in serviceHostBase.ChannelDispatchers)
      {
         ChannelDispatcher channelDispatcher = channelDispatcherBase as ChannelDispatcher;
         channelDispatcher.ErrorHandlers.Add(errorHandler);
      }
   }
}

附加到行为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[ServiceContract]
public interface IService
{
   [OperationContract(Action ="*", ReplyAction ="*")]
   Message Action(Message m);
}

[ErrorBehavior(typeof(HttpErrorHandler))]
public class Service : IService
{
   public Message Action(Message m)
   {
      throw new FaultException("!");
   }
}