【问题标题】:WebClient UploadString returns html code and does not send dataWebClient UploadString 返回html代码,不发送数据
【发布时间】:2019-09-10 14:30:32
【问题描述】:

我正在尝试使用以下代码将一些字符串从服务发送到 webmethod 服务:

private void SendRequest(string filePath, string webService)
{ 
    try
    {
         using (var wb = new WebClient())
         {
             string data = File.ReadAllText(filePath);
             data = "data=" + data;
             string res = wb.UploadString(webService, data);                 
         }
    }
    catch (Exception e)
    {
        logEvents.Write(MyLogClass.LogLevel.Info, "Data not sent " + e.Message);
    }
}        

由于某种原因,我不知道 res 正在返回首页的 html 代码。

我之前使用 node 执行此操作,我的 web 服务将毫无问题地接受字符串并返回 200。

web服务的代码开始如下:

[WebMethod]
public static string Data(string data)

我已尝试以多种方式格式化数据并更改参数和 URL 都很好。问题不在网络服务中,因为它适用于我的节点请求。会是什么?

【问题讨论】:

  • 您是否通过调试返回的内容来检查您的 Web 服务?
  • 当然。使用节点,它会返回一个包含请求的所有数据的 JSON。但是有了这个,它甚至没有进入网络服务。

标签: c# post webclient


【解决方案1】:

通过序列化正在发送的数据并使用 WebRequest 而不是 WebClient 解决了这个问题。

编辑

var webRequest = WebRequest.Create(webService);
                webRequest.Method = "POST";
                webRequest.ContentType = "application/json";
                string data = File.ReadAllText(filePath);
                var jsonObject = new { data };
                var serializedObject = JsonConvert.SerializeObject(jsonObject);
                var bytes = Encoding.ASCII.GetBytes(serializedObject);
                var requestStream = webRequest.GetRequestStream();
                requestStream.Write(bytes, 0, bytes.Length);
                HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();

【讨论】:

  • 请添加您用来解决问题的代码
  • 我编辑了条目以添加解决此问题的代码
【解决方案2】:

尝试明确指定Headers

using (var wb = new WebClient())
{
    wb.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
    string data = File.ReadAllText(filePath);
    data = "data=" + data;
    string res = wb.UploadString(webService, /*"POST",*/ data);
}

【讨论】:

  • 我仍然遇到同样的问题。 Web 服务返回一个字符串,其中包含 ```` "\r\n\r\n\r\n\r\n\r\n\r\n \r\n ... ```` 还不知道怎么回事。所有的参数和变量似乎都是对的。
  • 在输出窗口我得到这个异常:"System.Threading.ThreadAbortException' in mscorlib.dll"
  • 查看 html 正文的内容。它应该提到你得到的确切错误。另外,请确认您传递的网址 (webservice) 是否正确。看起来您正在访问主页 url 而不是 API 端点 url。
  • 我检查了它返回的字符串,它只包含首页内容,没有关于函数和网络服务的单一错误。
  • 方法的 URL 从 App.condig 文件中访问,如下所示: private string WebService = ConfigurationManager.AppSettings["WebService"];它是这样指定的: localhost:30571/myapp.aspx/Data">
猜你喜欢
  • 2017-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-18
  • 1970-01-01
  • 2023-03-27
相关资源
最近更新 更多