WCF服务将不会返回500内部服务器错误。相反,只有400错误的请求 [英] WCF service will not return 500 Internal Server Error. Instead, only 400 Bad Request

查看:189
本文介绍了WCF服务将不会返回500内部服务器错误。相反,只有400错误的请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个简单的RESTful WCF文件流媒体服务。当发生错误时,我想生成一个500 INTERAL服务器错误响应code。相反,只生成400错误的请求。
当请求是有效的,我得到了正确的响应(200 OK),但即使我抛出一个异常,我得到一个400。

I've created a simple RESTful WCF file streaming service. When an error occurs, I would like a 500 Interal Server Error response code to be generated. Instead, only 400 Bad Requests are generated. When the request is valid, I get the proper response (200 OK), but even if I throw an Exception I get a 400.

IFileService:

IFileService:

[ServiceContract]
public interface IFileService
{
    [OperationContract]
    [WebInvoke(Method = "GET",
        BodyStyle = WebMessageBodyStyle.Bare,
        ResponseFormat = WebMessageFormat.Json,
        UriTemplate = "/DownloadConfig")]
    Stream Download();
}

的FileService:

FileService:

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class GCConfigFileService : IGCConfigFileService
{
    public Stream Download()
    {
        throw new Exception();
    }
}

Web.Config中

Web.Config

<location path="FileService.svc">
<system.web>
  <authorization>
    <allow users="*"/>
  </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>

推荐答案

试用抛出新WebFaultException(的HTTPStatus code.InternalServerError);

要指定一个错误的详细信息:

To specify an error details:

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


高级:

如果你想更好地定义异常处理每个异常HTTP状态你需要创建一个自定义的ErrorHandler类,例如:


ADVANCED:

If you want better exception handling with defining HTTP status for each exception you'll need to create a custom ErrorHandler class for example:

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

然后你需要创建一个服务行为,以连接到您的服务:

Then you need to create a service behaviour to attach to your service:

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

附加到行为:

[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("!");
   }
}

这篇关于WCF服务将不会返回500内部服务器错误。相反,只有400错误的请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆