如何更改 WCF 中的默认 HTTP 方法



我是否必须在每个操作上方编写属性[WebGet]才能通过"GET"获得访问权限?我希望我的默认访问方法是"GET"而不是"POST"。有没有办法在web.config/app.config上做到这一点?

没有办法只在配置中做到这一点。您需要创建一个派生自 WebHttpBehavior 的新行为,并更改默认值(如果没有任何内容,请添加 [WebGet] ) - 请参阅下面的代码。然后,如果需要,可以定义行为配置扩展以通过配置使用该行为。

public class StackOverflow_10970052
{
    [ServiceContract]
    public class Service
    {
        [OperationContract]
        public int Add(int x, int y)
        {
            return x + y;
        }
        [OperationContract]
        public int Subtract(int x, int y)
        {
            return x + y;
        }
        [OperationContract, WebInvoke]
        public string Echo(string input)
        {
            return input;
        }
    }
    public class MyGetDefaultWebHttpBehavior : WebHttpBehavior
    {
        public override void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
        {
            foreach (var operation in endpoint.Contract.Operations)
            {
                if (operation.Behaviors.Find<WebGetAttribute>() == null && operation.Behaviors.Find<WebInvokeAttribute>() == null)
                {
                    operation.Behaviors.Add(new WebGetAttribute());
                }
            }
            base.ApplyDispatchBehavior(endpoint, endpointDispatcher);
        }
    }
    public static void Test()
    {
        string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
        ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
        host.AddServiceEndpoint(typeof(Service), new WebHttpBinding(), "").Behaviors.Add(new MyGetDefaultWebHttpBehavior());
        host.Open();
        Console.WriteLine("Host opened");
        WebClient c = new WebClient();
        Console.WriteLine(c.DownloadString(baseAddress + "/Add?x=6&y=8"));
        c = new WebClient();
        Console.WriteLine(c.DownloadString(baseAddress + "/Subtract?x=6&y=8"));
        c = new WebClient();
        c.Headers[HttpRequestHeader.ContentType] = "application/json";
        Console.WriteLine(c.UploadString(baseAddress + "/Echo", ""hello world""));
        Console.Write("Press ENTER to close the host");
        Console.ReadLine();
        host.Close();
    }
}

最新更新