asp.net - asmx 网络服务不读取 postdata

标签 asp.net web-services webforms asmx

我有一个 .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/

相关文章:

c# - Repeater 中的按钮不会触发 ItemCommand

java - PHP 和 Java 编码问题

c# - 如何通过ID来操作itemtemplate中的item

asp.net - 如何在 ASP.Net MVC 中执行 301 永久重定向路由

asp.net - 使用 Web.Config 转换插入多个项目

数组上的 C# OutOfMemoryException

.net - 在 .Net 中替代手动构建表/TR/TD?

c# - 在 asp.net gridview 中更改选定行的颜色

html - 具有不透明度值的悬停背景和具有不同不透明度值的悬停按钮

web-services - 可以(和/或一个好主意)在应用程序之间重用 OAuth token 吗?