Web API : 远程服务器返回错误。 (500内部服务器错误。仅当在线且不在本地计算机中时

Web API : The remote server returned an error. (500) Internal Server Error. Only when online and not in Local Machine

问题来了。我正在使用 ASP.NET Web API 与我的项目集成,并将请求 URL 存储在 web.config 中。在我的代码中,我使用这些 URL 来触发对 Web API 的请求并发送和接收数据。 URL 工作正常,我可以向你保证。这里的问题是这个单一的 URL。

当我 运行 在本地机器上进行项目并且数据流正常时,它就可以工作了。但是当我在托管后在线测试 运行 时,相同的服务无法向我发送数据。相反,我在 catch 块中收到以下异常:

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

我已经确认以下内容是真实和正确的:

  1. 两个项目中的连接字符串。
  2. 没有拼写错误。
  3. 没有错误URL.
  4. 在本地调试时,没有报错,成功进行。
  5. 完美地在本地工作并接收正确的数据,只是不能在线工作。

我也试过重新托管。但还是一样。不确定这里可能是什么问题。

控制器方法代码如下:

using (var client = new WebClient())
{
   Model serviceModel = new Model();
   serviceModel.Number = Num;
   serviceModel.type = "getalldetails";
   client.Headers[HttpRequestHeader.ContentType] = "application/json";
   JavaScriptSerializer serializer = new JavaScriptSerializer();
   var result = client.UploadData(System.Web.Configuration.WebConfigurationManager.AppSettings["GetDetails"], Encoding.UTF8.GetBytes(serializer.Serialize(serviceModel)));//this is the exception point
}

这是web.config URL:

<add key="GetDetails" value="http://hostname/api/controller/GetDetails" />

此外,我在 Web API 端设置了错误日志以防出现错误请求或类似情况,但在这种情况下不会插入新记录。所以这让我很困惑,不知道问题出在哪里。

异常是这样的:

System.Net.WebException was caught HResult=-2146233079 Message=The remote server returned an error: (500) Internal Server Error.
Source=System StackTrace: at System.Net.WebClient.UploadDataInternal(Uri address, String method, Byte[] data, WebRequest& request) at System.Net.WebClient.UploadData(Uri address, String method, Byte[] data) at System.Net.WebClient.UploadData(String address, Byte[] data)

这就是我将我的 json 对象序列化为字符串并将 json 发送到网络 api 的方式,只是为了帮助:

//Get the json
private JsonResult GetJsonResult()
{
    //whatever json you are expecting on api side
    return Json(new { Number = "Num", type = "getalldetails" });
}

private void Update()
{
    var URI = new Uri("http://hostname/api/controller/GetDetails");
    //serialize json object to string, .Data just to get json data
    string jsonText = JsonConvert.SerializeObject(GetJsonResult().Data);

    //post to api
    using (var client = new WebClient())
    {
        client.Encoding = Encoding.UTF8;
        client.Headers.Add("Content-Type", "text/json");
        client.UploadString(URI, "POST", jsonText);
    }
}

并且我在 Web api 端启用了跨域。

好久没看到了

现在我几乎在看我想到的每一种可能性,并在评论和答案中提出建议。

第二天,当我尝试同样的事情时,它运行顺利!

所以我得出结论,可能问题出在服务器端。我使用 Azure,在那个特定的日子,它 可能 有一些问题,并且可能导致 500:内部服务器错误。从那以后它一直运行良好。