通过WCF服务消费形式的数据通过邮局
问题描述:
送我了解一些这方面的文章,我发现,才达到该WCF得到POST请求的数据,我们添加通过WCF服务消费形式的数据通过邮局
[ServiceContract]
public interface IService1 {
[OperationContract]
[WebInvoke(
Method = "POST",
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "/GetData")]
void GetData(Stream data);
}
,并在实施
public string GetData(Stream input)
{
long incomingLength = WebOperationContext.Current.IncomingRequest.ContentLength;
string[] result = new string[incomingLength];
int cnter = 0;
int arrayVal = -1;
do
{
if (arrayVal != -1) result[cnter++] = Convert.ToChar(arrayVal).ToString();
arrayVal = input.ReadByte();
} while (arrayVal != -1);
return incomingLength.ToString();
}
我的问题是我应该怎么做,在提交表单请求的行动将发送到我的服务和消费?
在Stream参数中,我是否可以通过Request [“FirstName”]从表单中获取发布信息?
答
您的代码没有正确解码请求正文 - 您正在创建一个数值为string
的值,每个值都包含一个字符。得到请求体后,你需要解析查询字符串(使用HttpUtility
是一个简单的方法)。下面的代码显示了如何正确获取主体和其中一个字段。
public class *_7228102
{
[ServiceContract]
public interface ITest
{
[OperationContract]
[WebInvoke(
Method = "POST",
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "/GetData")]
string GetData(Stream data);
}
public class Service : ITest
{
public string GetData(Stream input)
{
string body = new StreamReader(input).ReadToEnd();
NameValueCollection nvc = HttpUtility.ParseQueryString(body);
return nvc["FirstName"];
}
}
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();
c.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
Console.WriteLine(c.UploadString(baseAddress + "/GetData", "FirstName=John&LastName=Doe&Age=33"));
Console.Write("Press ENTER to close the host");
Console.ReadLine();
host.Close();
}
}
这是很好的解决方案Tnx;)但是在Test方法中,您调用服务并发送给它发送请求。在以
是的,它应该工作(测试方法模拟HTML表单发送的内容)。问题是,当你默认做一个表单提交时,你应该创建一个HTML页面来发送它(而不是一个简单的字符串),否则浏览器将只显示你返回的字符串。另一个选择是在submit表单中使用一些ajax调用,然后您可以将结果作为XML(或JSON)返回并以内联方式更新页面。 – carlosfigueira