WCF休息奇怪的路由行为

时间:2012-05-02 22:44:50

标签: wcf rest routing

我有资源可用 http://localhost/resource

我没有任何路线 HTTP:/本地主机/资源名=约翰

但是当我尝试点击上面的URI时,我得到http://localhost/resource的结果。我期待着404。

知道它为什么忽略?name = john并匹配url ??

1 个答案:

答案 0 :(得分:0)

查询字符串参数是可选的,而不是“正式”地址的一部分 - 它从方案到路径(通过主机和端口)。在许多情况下,您在地址http://something.com/path处有一个操作,而在操作代码中 ,您会查看查询字符串参数以做出一些决定。例如,下面的代码在查询字符串中查找可能会或可能不会传递的“format”参数,并且所有请求(包含或不包含)都会正确路由到操作。

public class StackOverflow_10422764
{
    [DataContract(Name = "Person", Namespace = "")]
    public class Person
    {
        [DataMember]
        public string Name { get; set; }
        [DataMember]
        public int Age { get; set; }
    }
    [ServiceContract]
    public class Service
    {
        [WebGet(UriTemplate = "/NoQueryParams")]
        public Person GetPerson()
        {
            string format = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters["format"];
            if (format == "xml")
            {
                WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Xml;
            }
            else if (format == "json")
            {
                WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Json;
            }

            return new Person { Name = "Scooby Doo", Age = 10 };
        }
    }
    public static void Test()
    {
        string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
        WebServiceHost host = new WebServiceHost(typeof(Service), new Uri(baseAddress));
        host.Open();
        Console.WriteLine("Host opened");

        WebClient c = new WebClient();
        Console.WriteLine(c.DownloadString(baseAddress + "/NoQueryParams"));

        c = new WebClient();
        Console.WriteLine(c.DownloadString(baseAddress + "/NoQueryParams?format=json"));

        Console.Write("Press ENTER to close the host");
        Console.ReadLine();
        host.Close();
    }
}

评论后更新: 如果要强制请求完全包含模板中指定的参数,则可以使用消息检查器之类的内容来验证。

public class StackOverflow_10422764
{
    [DataContract(Name = "Person", Namespace = "")]
    public class Person
    {
        [DataMember]
        public string Name { get; set; }
        [DataMember]
        public int Age { get; set; }
    }
    [ServiceContract]
    public class Service
    {
        [WebGet(UriTemplate = "/NoQueryParams")]
        public Person GetPerson()
        {
            string format = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters["format"];
            if (format == "xml")
            {
                WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Xml;
            }
            else if (format == "json")
            {
                WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Json;
            }

            return new Person { Name = "Scooby Doo", Age = 10 };
        }

        [WebGet(UriTemplate = "/TwoQueryParam?x={x}&y={y}")]
        public int Add(int x, int y)
        {
            return x + y;
        }
    }
    public class MyForceQueryMatchBehavior : IEndpointBehavior, IDispatchMessageInspector
    {
        #region IEndpointBehavior Members

        public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
        {
        }

        public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
        {
        }

        public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
        {
            endpointDispatcher.DispatchRuntime.MessageInspectors.Add(this);
        }

        public void Validate(ServiceEndpoint endpoint)
        {
        }

        #endregion

        #region IDispatchMessageInspector Members

        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            UriTemplateMatch uriTemplateMatch = (UriTemplateMatch)request.Properties["UriTemplateMatchResults"];

            // TODO: may need to deal with the case of implicit UriTemplates, or if you want to allow for some query parameters to be ommitted

            List<string> uriTemplateQueryVariables = uriTemplateMatch.Template.QueryValueVariableNames.Select(x => x.ToLowerInvariant()).ToList();
            List<string> requestQueryVariables = uriTemplateMatch.QueryParameters.Keys.OfType<string>().Select(x => x.ToLowerInvariant()).ToList();
            if (uriTemplateQueryVariables.Count != requestQueryVariables.Count || uriTemplateQueryVariables.Except(requestQueryVariables).Count() > 0)
            {
                throw new WebFaultException(HttpStatusCode.NotFound);
            }

            return null;
        }

        public void BeforeSendReply(ref Message reply, object correlationState)
        {
        }

        #endregion
    }
    static void SendRequest(string uri)
    {
        Console.WriteLine("Request to {0}", uri);
        WebClient c = new WebClient();
        try
        {
            Console.WriteLine("  {0}", c.DownloadString(uri));
        }
        catch (WebException e)
        {
            HttpWebResponse resp = e.Response as HttpWebResponse;
            Console.WriteLine("  ERROR => {0}", resp.StatusCode);
        }
    }
    public static void Test()
    {
        string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
        ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
        ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(Service), new WebHttpBinding(), "");
        endpoint.Behaviors.Add(new WebHttpBehavior());
        endpoint.Behaviors.Add(new MyForceQueryMatchBehavior());
        host.Open();
        Console.WriteLine("Host opened");

        SendRequest(baseAddress + "/NoQueryParams");
        SendRequest(baseAddress + "/NoQueryParams?format=json");
        SendRequest(baseAddress + "/TwoQueryParam?x=7&y=9&z=other");
        SendRequest(baseAddress + "/TwoQueryParam?x=7&y=9");

        Console.Write("Press ENTER to close the host");
        Console.ReadLine();
        host.Close();
    }
}