发布数据必须是键值对?如果不是如何在.Net中读取原始数据

时间:2015-04-10 03:25:21

标签: asp.net post

我不认为它必须是成对的,所以如果我发送如下的纯文本:

HttpClient httpClient = new HttpClient();

httpClient.PostAsync("http://hey.com", 
new StringContent("simple string, no key value pair."));

然后下面的FormCollection似乎没有提供一种方法来阅读..

public ActionResult Index(FormCollection collection){

    //how to get the string I sent from collection?
}

1 个答案:

答案 0 :(得分:1)

FormCollection对象是键值对集合。如果您要发送一个简单的字符串,那么除非将其格式化为Key \ Value对,否则该集合将为空。

这可以通过多种方式完成。

选项1:发送键值对,FormCollection将使用键myString读取您的字符串:

HttpClient httpClient = new HttpClient();
var content = new FormUrlEncodedContent(new[] 
{
    new KeyValuePair<string, string>("mystring", "My String Value")
});
httpClient.PostAsync("http://myUrl.com", content);

选项2:直接从请求中读取内容。这会将原始Request.InputStream读入StreamReader到字符串

public ActionResult ReadInput()
{
    this.Request.InputStream.Seek(0, System.IO.SeekOrigin.Begin);
    string myString = "";
    using (var reader = new StreamReader(this.Request.InputStream))
    {
        myString = reader.ReadToEnd();
    }
}

还有更多选择,但这些方法中的任何一种都应该做到这一点

相关问题