2012-10-02 74 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

相關問題