【问题标题】:Calling methods from .ashx handler from aspx.cs page从 aspx.cs 页面调用 .ashx 处理程序的方法
【发布时间】:2013-07-23 13:50:07
【问题描述】:

我在从我们拥有的通用处理程序调用方法时遇到了一些麻烦。我尝试使用两种不同的技术来调用一个简单的“HelloWorld()”方法,但我得到了两个不同的错误:

第一种技术如下:

        WebClient wc = new WebClient();

        NameValueCollection formData = new NameValueCollection();
        formData["method"] = "HelloWorld";


        byte[] data;

        try
        {
            data = wc.UploadValues(_domain, formData);
        }
        catch (WebException ex)
        {
            Label1.Text = ex.Message;
            return;
        }

        string response = Encoding.UTF8.GetString(data);
        Label1.Text = response;

        wc.Dispose();

我收到以下错误:

{"id":null,"error":{"name":"Found String where Object was expected."}}

我尝试过的第二种技术是:

            var httpWebRequest = (HttpWebRequest)WebRequest.Create(_domain);
        httpWebRequest.ContentType = "text/json";
        httpWebRequest.Method = "POST";

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string json = "{\"method\":\"helloWorld\"}"; //," +
            //"\"password\":\"bla\"}";

            streamWriter.Write(json);
            streamWriter.Flush();
            streamWriter.Close();

            try
            {
                var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    var result = streamReader.ReadToEnd();
                }
            }
            catch (WebException wex)
            {
                Label2.Text = wex.Message;
            }
            catch (Exception ex)
            {
                Label2.Text = ex.Message;
            }
        }

因此,我收到以下错误:

The remote server returned an error: (500) Internal Server Error.

当我从“.ashx?test”页面测试调用时,方法运行并且屏幕底部的详细信息是:

Pragma: no-cache
Date: Tue, 23 Jul 2013 13:46:19 GMT
Server: ASP.NET Development Server/11.0.0.0
X-AspNet-Version: 2.0.50727
Content-Type: application/json; charset=utf-8
Cache-Control: no-cache
Connection: Close
Content-Length: 32
Expires: -1

关于为什么这不起作用的任何想法?

谢谢!

【问题讨论】:

  • 永远不需要从 aspx 页面调用 ashx 处理程序。重构您的代码,以便将 ashx 处理程序中的逻辑移至可重用类。
  • @BradM 也许它在不同的服务器上......
  • @BradM 不幸的是,在这种情况下我们需要这样做。
  • @Mr47 可能,但他说这是“我们”拥有的处理程序。

标签: c# asp.net json web-services ashx


【解决方案1】:

ASHX 处理程序不是 Web 服务。您不会在 ASXH 处理程序中调用方法。您只需调用处理程序,它就会直接传递数据,无论是文本数据还是二进制数据 - 这取决于您。

【讨论】:

  • 调用处理程序的最佳方法是什么?请记住,我无法重构任何东西。
  • 在浏览器中调用 ASHX 时会看到什么? HelloWorld 应该返回什么?
  • 它返回 json 而这个特定的方法只是返回一个字符串。
  • 好吧,您只能使用处理程序返回的内容。发出 WebRequest,并使用响应内容。应该是纯文本。
  • 好的,那太好了,我会试一试。感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-14
  • 1970-01-01
  • 1970-01-01
  • 2013-03-30
  • 2012-01-08
相关资源
最近更新 更多