我有一个 .asmx 网络服务,除了不读取 prostdata 之外,它工作正常。它看起来像这样:
namespace mynamespace.liby
{
[ScriptService]
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class json : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<sp_tech_keywordSearch_Result> search()
{
const string KEY = "key";
var key = string.Empty;
// convert postdata to dictionary
// this piece of code works fine in my asp.net MVC controller but not here :-(
string data = new StreamReader(HttpContext.Current.Request.InputStream).ReadToEnd();
Dictionary<string, string> postData = JsonConvert.DeserializeObject<Dictionary<string, string>>(data);
if (postData.ContainsKey(KEY)) { key = postData[KEY]; }
var db = new my_Entities();
var result = db.sp_myStoredProcedure(key);
return result.ToList();
}
}
}
如果我注释掉这一行
// if (postData.ContainsKey(KEY)) { key = postData[KEY]; }
该过程在没有参数的情况下被调用并返回一个值列表。
但是当我保留这条线时,它会抛出一个错误说
postData
一片空白。当我在 Debug模式下检查它时,我看到
data
是一个空字符串。我用这样的 angular 调用这个服务:
callService: function () {
var postData = new Object();
postData.key =4;
return $http({ method: 'POST', url: MY_SERVICE, data: postData })
.then(function (obj) {
_Result = obj.data.d;
return true;
}, function (err) {
_Result = [];
console.log('serviceError');
return false;
});
},
我的猜测是我读取 postdata 的代码不知何故是错误的。我在 ASP.NET MVC Controller 中运行了相同的代码,并且在那里运行良好。有没有人知道如何解决这个问题?
最佳答案
添加这个解决了问题
// goto beginning of the inputstream
HttpContext.Current.Request.InputStream.Position = 0;
// convert postdata to dictionary
string data = new StreamReader(HttpContext.Current.Request.InputStream).ReadToEnd();
由于某种原因,输入流的“光标”位于最后一个位置和
ReadToEnd()
导致读取空字符串。
关于asp.net - asmx 网络服务不读取 postdata,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24039708/