【问题标题】:asmx webservice doesn't read postdataasmx webservice 不读取 postdata
【发布时间】:2014-06-04 14:07:51
【问题描述】:

我有一个运行良好的 .asmx 网络服务,但它不读取前列腺数据。它看起来像这样:

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 为空。 当我在调试模式下检查它时,我看到 data 是一个空字符串。

我用这样的角度调用这个服务:

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 控制器中运行了相同的代码,并且在那里运行良好。有没有人知道如何解决这个问题?

【问题讨论】:

    标签: asp.net web-services webforms asmx


    【解决方案1】:

    添加这个解决了问题

    // 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() 导致读取空字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-30
      相关资源
      最近更新 更多