在WCF休息服务中处理404

时间:2011-06-16 12:32:56

标签: c# wcf rest exception-handling

我在IIS 7.5上有一个wcf rest服务。当有人访问不存在的端点的一部分时(即http://localhost/rest.svc/DOESNOTEXIST vs http://localhost/EXISTS),他们会看到一个带有状态代码404的Generic WCF灰色和蓝色错误页面。但是,我想返回如下内容:

<service-response>
   <error>The url requested does not exist</error>
</service-response>

我尝试在IIS中配置自定义错误,但只有在请求其余服务之外的页面时才会有效(即http://localhost/DOESNOTEXIST)。

有谁知道怎么做?

修改 在下面的答案之后,我能够弄清楚我需要创建一个实现BehaviorExtensionElement的WebHttpExceptionBehaviorElement类。

 public class WebHttpExceptionBehaviorElement : BehaviorExtensionElement
 {
    ///  
    /// Get the type of behavior to attach to the endpoint  
    ///  
    public override Type BehaviorType
    {
        get
        {
            return typeof(WebHttpExceptionBehavior);
        }
    }

    ///  
    /// Create the custom behavior  
    ///  
    protected override object CreateBehavior()
    {
        return new WebHttpExceptionBehavior();
    }  
 }

然后我可以通过以下方式在我的web.config文件中引用它:

<extensions>
  <behaviorExtensions>
    <add name="customError" type="Service.WebHttpExceptionBehaviorElement, Service"/>
  </behaviorExtensions>
</extensions>

然后添加

<customError /> 

到我的默认端点行为。

谢谢,

Jeffrey Kevin Pry

2 个答案:

答案 0 :(得分:5)

首先,创建一个子类WebHttpBehavior的自定义行为 - 在这里你将删除默认的Unhandled Dispatch Operation处理程序,并附加你自己的:

public class WebHttpBehaviorEx : WebHttpBehavior
{
    public override void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
    {
        base.ApplyDispatchBehavior(endpoint, endpointDispatcher);

        endpointDispatcher.DispatchRuntime.Operations.Remove(endpointDispatcher.DispatchRuntime.UnhandledDispatchOperation);
        endpointDispatcher.DispatchRuntime.UnhandledDispatchOperation = new DispatchOperation(endpointDispatcher.DispatchRuntime, "*", "*", "*");
        endpointDispatcher.DispatchRuntime.UnhandledDispatchOperation.DeserializeRequest = false;
        endpointDispatcher.DispatchRuntime.UnhandledDispatchOperation.SerializeReply = false;
        endpointDispatcher.DispatchRuntime.UnhandledDispatchOperation.Invoker = new UnknownOperationInvoker();

    }
}

然后。制作未知的操作处理程序。该类将处理未知操作请求并生成作为响应的“消息”。我已经展示了如何创建纯文本消息。为您的目的修改它应该是相当直接的:

internal class UnknownOperationInvoker : IOperationInvoker
{
    public object[] AllocateInputs()
    {
        return new object[1];
    }


    private Message CreateTextMessage(string message)
    {
        Message result = Message.CreateMessage(MessageVersion.None, null, new HelpPageGenerator.TextBodyWriter(message));
        result.Properties["WebBodyFormatMessageProperty"] = new WebBodyFormatMessageProperty(WebContentFormat.Raw);
        WebOperationContext.Current.OutgoingResponse.ContentType = "text/html";
        return result;
    }

    public object Invoke(object instance, object[] inputs, out object[] outputs)
    {
        // Code HERE

                StringBuilder builder = new System.Text.StringBuilder();

                builder.Append("...");

                Message result = CreateTextMessage(builder.ToString());

                return result;
    }

    public System.IAsyncResult InvokeBegin(object instance, object[] inputs, System.AsyncCallback callback, object state)
    {
        throw new System.NotImplementedException();
    }

    public object InvokeEnd(object instance, out object[] outputs, System.IAsyncResult result)
    {
        throw new System.NotImplementedException();
    }

    public bool IsSynchronous
    {
        get { return true; }
    }
}

此时,您必须将新行为与您的服务相关联。

有几种方法可以做到这一点,所以请问你是否还不知道,我将很乐意进一步阐述。

答案 1 :(得分:1)

我遇到了类似的问题,另一个答案确实导致了我最终的成功,这不是最清楚的答案。以下是我解决这个问题的方法。

我的项目设置是作为在IIS中托管的svc托管的WCF服务。我无法使用配置路由来添加行为,因为我的程序集版本会因为持续集成而更改每次签入。

为了克服这个障碍,我创建了一个自定义的ServiceHostFactory:

using System.ServiceModel;
using System.ServiceModel.Activation;

namespace your.namespace.here
{
    public class CustomServiceHostFactory : WebServiceHostFactory
    {
        protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
        {
            ServiceHost host = base.CreateServiceHost(serviceType, baseAddresses);
            //note: these endpoints will not exist yet, if you are relying on the svc system to generate your endpoints for you
            // calling host.AddDefaultEndpoints provides you the endpoints you need to add the behavior we need.
            var endpoints = host.AddDefaultEndpoints();
            foreach (var endpoint in endpoints)
            {
                endpoint.Behaviors.Add(new WcfUnkownUriBehavior());
            }

            return host;
        }
    }
}

如您所见,我们正在添加一个新行为:WcfUnknownUriBehavior。这种新的自定义行为的灵魂职责是替换UnknownDispatcher。以下是该实施:

using System.ServiceModel.Dispatcher;
using System.ServiceModel.Channels;
using System.ServiceModel.Web;
namespace your.namespace.here
{
    public class UnknownUriDispatcher : IOperationInvoker
    {
        public object[] AllocateInputs()
        {
            //no inputs are really going to come in,
            //but we want to provide an array anyways
            return new object[1]; 
        }

        public object Invoke(object instance, object[] inputs, out object[] outputs)
        {
            var responeObject = new YourResponseObject()
            {
                Message = "Invalid Uri",
                Code = "Error",
            };
            Message result = Message.CreateMessage(MessageVersion.None, null, responeObject);
            WebOperationContext.Current.OutgoingResponse.ContentType = "text/html";
            outputs = new object[1]{responeObject};
            return result;
        }

        public System.IAsyncResult InvokeBegin(object instance, object[] inputs, System.AsyncCallback callback, object state)
        {
            throw new System.NotImplementedException();
        }

        public object InvokeEnd(object instance, out object[] outputs, System.IAsyncResult result)
        {
            throw new System.NotImplementedException();
        }

        public bool IsSynchronous
        {
            get { return true; }
        }
    }
}

一旦指定了这些对象,您现在可以在svc的“标记”中使用新工厂:

<%@ ServiceHost Language="C#" Debug="true" Service="your.service.namespace.here" CodeBehind="myservice.svc.cs"
                Factory="your.namespace.here.CustomServiceHostFactory" %>

那应该是它。只要您的对象“YourResponseObject”可以被序列化,它的序列化表示将被发送回客户端。