我是否必须在[WebGet]
每个操作上方写入属性才能通过“GET”访问?我希望我的默认访问方法是“GET”而不是“POST”。有没有办法在 web.config/app.config 上做到这一点?
问问题
1494 次
1 回答
1
没有办法只在配置中做到这一点。您需要创建一个从 派生的新行为,WebHttpBehavior
并更改默认值(如果没有,请添加 [WebGet]) - 请参见下面的代码。然后,如果您愿意,您可以定义一个行为配置扩展以通过 config.xml 使用该行为。
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();
}
}
于 2012-06-11T19:34:14.793 回答