2012-10-02 49 views
1

我已经创建了一个简单的RESTful WCF文件流服务。发生错误时,我想要生成一个500 Interal Server Error响应代码。相反,仅生成400个错误请求。 当请求是有效的,我得到了正确的响应(200 OK),但即使我抛出一个异常,我得到一个400WCF服务不会返回500内部服务器错误。相反,只有400个错误请求

IFileService:

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

的FileService:

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

的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> 

回答

3

简单:

试用throw new WebFaultException(HttpStatusCode.InternalServerError);

要指定一个错误信息:

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

ADVANCED:

如果你想更好的异常,并确定HTTP status每个异常处理您需要创建一个自定义的ErrorHandler类,例如:

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

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

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

感谢您的答复。我尝试了'抛出新的FaultException(“!”)'但这对我不起作用(仍然得到400)。看来FaultException应该用于基于SOAP的服务,而我的服务不是。我正在使用基于REST的方法。 – Darcy

+0

已更新的答案,让我知道它是否适用于** WebFaultException **。 – Danpe

+0

WebFaultException确实会创建500内部服务器错误,但是没有办法设置错误消息吗?我想返回一个原因,但WebFaultException类不允许我设置它。 – Darcy

相关问题