Asp.net 通过邮寄发送wcf服务使用表单数据
我读了一些关于这方面的文章,我发现为了实现wcf从post请求中获取数据,我们添加了Asp.net 通过邮寄发送wcf服务使用表单数据,asp.net,wcf,forms,post,Asp.net,Wcf,Forms,Post,我读了一些关于这方面的文章,我发现为了实现wcf从post请求中获取数据,我们添加了 [ServiceContract] public interface IService1 { [OperationContract] [WebInvoke( Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/GetData")] void GetData(Stream da
[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参数中,我是否可以从表单中获得post信息,通过请求[“FirstName”]?您的代码没有正确解码请求正文-您正在创建一个
字符串
值数组,每个值都有一个字符。获取请求正文后,需要解析查询字符串(使用HttpUtility
是一种简单的方法)。下面的代码显示了如何正确获取正文和其中一个字段
public class StackOverflow_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;)但在测试方法中,调用服务并向其发送post请求。在提交后以如下形式调用服务方法是可能的(也是明智的做法)?如果我这样做,它会起作用吗?:)是的,它应该可以工作(测试方法模拟HTML表单post将发送的内容)。问题是,当您在默认情况下执行表单提交时,您应该创建一个HTML页面以将其发回(而不是一个简单的字符串),否则浏览器将只显示该字符串。另一个选项是在表单submit中使用一些ajax调用,然后您可以将结果作为XML(或JSON)返回并内联更新页面。