gpt4 book ai didi

wcf - WCF 中 UriTemplate 中的可选参数

转载 作者:行者123 更新时间:2023-12-04 04:52:24 25 4
gpt4 key购买 nike

我已经使用了 this thread 中的提示并提供了一个默认值,以便当用户没有指定虚拟子目录时,我假设他的意思是要列出所有内容。它有效。

[OperationContract]
[WebInvoke(UriTemplate = "GetStuff/{type=all}", ...]
IEnumerable<Stuff> GetStuff(String type);

但是,最好指定一个默认值。但是, default(String) 为空,我想发送一个实际值。特别是,我对 String.Empty 一心一意。但是,我注意到以下内容不起作用。服务器端的条件无法识别空字符串(... where 'type' in (ColName, '', 'all'))。
[OperationContract]
[WebInvoke(UriTemplate = "GetStuff/{type=String.Empty}", ...]
IEnumerable<Stuff> GetStuff(String type);

怎么办?

最佳答案

您不能在 UriTemplate 中真正拥有一个空的默认值,但是您可以拥有一些意味着默认值的东西,并且在操作中您可以将其替换为您想要的实际默认值,如下所示。

public class StackOverflow_17251719
{
const string DefaultValueMarker = "___DEFAULT_VALUE___";
const string ActualDefaultValue = "";
[ServiceContract]
public class Service
{
[WebInvoke(UriTemplate = "GetStuff/{type=" + DefaultValueMarker + "}", ResponseFormat = WebMessageFormat.Json)]
public IEnumerable<string> GetStuff(String type)
{
if (type == DefaultValueMarker)
{
type = ActualDefaultValue;
}

yield return type;
}
}
public static void SendBodylessPostRequest(string uri)
{
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uri);
req.Method = "POST";
req.ContentType = "application/json";
req.GetRequestStream().Close(); // no request body

HttpWebResponse resp;
try
{
resp = (HttpWebResponse)req.GetResponse();
}
catch (WebException e)
{
resp = (HttpWebResponse)e.Response;
}

Console.WriteLine("HTTP/{0} {1} {2}", resp.ProtocolVersion, (int)resp.StatusCode, resp.StatusDescription);
foreach (string headerName in resp.Headers.AllKeys)
{
Console.WriteLine("{0}: {1}", headerName, resp.Headers[headerName]);
}

Console.WriteLine();
Stream respStream = resp.GetResponseStream();
Console.WriteLine(new StreamReader(respStream).ReadToEnd());

Console.WriteLine();
Console.WriteLine(" *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* ");
Console.WriteLine();
}
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");

SendBodylessPostRequest(baseAddress + "/GetStuff/nonDefault");
SendBodylessPostRequest(baseAddress + "/GetStuff");

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

关于wcf - WCF 中 UriTemplate 中的可选参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17251719/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com