尝试使用 this code
我已经走到了死胡同 在客户端,表单值被收集和序列化,但由于不可能在静态方法中使用请求实例 我未能在服务器上收到序列化表单值, 我尝试使用静态 HttpContext.Current.Request.InputStream 绕过它 但我得到了空流。 我如何获取服务器中的输入流? 客户端:
function myFunction() {
$.ajax({
type: "POST",
url: "ajaxForm.aspx/Receiver",
contentType: "application/json; charset=utf-8",
data: $('#myForm').serialize(),
datatype : "json",
cache: false,
success: function (data) {
$('#result').html(data);
},
error: function (data) {
alert('failed');
}
});
}
服务器端第一个版本(从该链接复制):
{
string json;
using(var reader = new StreamReader(Request.InputStream)){
json = reader.ReadToEnd();
}
第二个版本:
[WebMethod ]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static void Receiver()
{
if (HttpContext.Current.Request.InputStream.Position != 0)
{
HttpContext.Current.Request.InputStream.Seek(0,System.IO.SeekOrigin.Begin);
}
byte[] data = new byte[HttpContext.Current.Request.InputStream.Length];
HttpContext.Current.Request.InputStream.Read(data, 0, data.Length);}
最佳答案
目前您的数据看起来不像 JSON。尝试这样。
var jsonData = JSON.stringify({
form: $('#myForm').serialize()
});
在ajax调用数据
...
contentType: "application/json; charset=utf-8",
data: jsonData,
datatype : "json",
...
你的方法:
[WebMethod ]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static void Receiver(string form)
{
//in the string form you should have myForm serialize.
}
如果你想使用 Context.Session 来做某事,你需要启用它。
[System.Web.Services.WebMethod(EnableSession = true)]
关于c# - 使用 jquery ajax 调用 ASP.NET 静态方法中的输入流来发布表单值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34917965/