Я вытягиваю свои волосы на этом. Я не могу успешно вызвать веб-службу .NET с помощью POST и JSON («Удаленный сервер ответил на ошибку: (500)« Внутренняя ошибка сервера ».). Я могу заставить его работать, если я не настаиваю на JSON или если я использую GET. Я делаю все это в Xamarin Studio, поэтому веб-сервер XSP, а не IIS, если это имеет значение.Ошибка при вызове веб-службы ASP.NET с использованием POST и JSON
Факс: справка много оценено.
Вот код для моего веб-сервиса:
using System;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Web.Script.Serialization;
namespace WebServiceTest
{
[WebService (Namespace = "http://tempuri.org/WebServiceTest")]
[ScriptService]
public class API : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod (UseHttpGet=true, ResponseFormat=ResponseFormat.Json)]
public string About() {
return "About WebServiceTest";
}
}
}
... вот мой web.config ...
<?xml version="1.0"?>
<!--
Web.config file for WebServiceTest.
The settings that can be used in this file are documented at
http://www.mono-project.com/Config_system.web and
http://msdn2.microsoft.com/en-us/library/b5ysx397.aspx
-->
<configuration>
<system.web>
<webServices>
<protocols>
<add name="HttpGet" />
<add name="HttpPost" />
</protocols>
</webServices>
<compilation defaultLanguage="C#" debug="true">
<assemblies>
</assemblies>
</compilation>
<customErrors mode="RemoteOnly">
</customErrors>
<authentication mode="None">
</authentication>
<authorization>
<allow users="*" />
</authorization>
<httpHandlers>
</httpHandlers>
<trace enabled="false" localOnly="true" pageOutput="false" requestLimit="10" traceMode="SortByTime" />
<sessionState mode="InProc" cookieless="false" timeout="20" />
<globalization requestEncoding="utf-8" responseEncoding="utf-8" />
<pages>
</pages>
</system.web>
</configuration>
... и вот мой тест кода приложения. ..
using System;
using System.IO;
using System.Net;
using System.Text;
namespace WebServiceTestApp
{
class MainClass
{
public static void Main (string[] args)
{
Console.WriteLine ("Starting...");
Console.WriteLine ("Making API call...");
string url = "http://127.0.0.1:8080/API.asmx/About";
HttpWebRequest request;
// Test 1: Use GET, don't set content type or content
// Works, returns XML
Console.WriteLine ("Test 1");
request = (HttpWebRequest)WebRequest.Create (url);
GetResponse (request);
// Test 2: Use GET, set content type but no content
// Works, returns JSON
Console.WriteLine ("Test 2");
request = (HttpWebRequest)WebRequest.Create (url);
request.ContentType = "application/json; charset=utf-8";
GetResponse (request);
// Test 3: Use POST, don't set content type or content
// Works, returns XML
Console.WriteLine ("Test 3");
request = (HttpWebRequest)WebRequest.Create (url);
request.Method = "POST";
GetResponse (request);
// Test 4: Use POST, set content type but no content
// *** Fails: 500 Internal Server Error
Console.WriteLine ("Test 4");
request = (HttpWebRequest)WebRequest.Create (url);
request.ContentType = "application/json; charset=utf-8";
request.Method = "POST";
GetResponse (request);
// Done.
Console.WriteLine ("Done!");
}
public static void GetResponse(HttpWebRequest request)
{
try {
using (var response = (HttpWebResponse)request.GetResponse()) {
var stream = response.GetResponseStream();
var reader = new StreamReader (stream);
var result = reader.ReadToEnd();
Console.WriteLine (result);
reader.Close();
reader.Dispose();
response.Close();
}
} catch (Exception e) {
Console.WriteLine ("*** Failed: Error '" + e.Message + "'.");
}
}
}
}
тест также терпит неудачу, если я пытаюсь добавить любое содержимое в POST, запрос, то есть замена кода Test 4 с ...
// Test 4: Use POST, set content type and content
// *** Fails: 500 Internal Server Error
Console.WriteLine ("Test 4");
request = (HttpWebRequest)WebRequest.Create (url);
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
var paramData = ""; // also fails with "{}"
request.ContentLength = paramData.Length;
using (var writer = new StreamWriter (request.GetRequestStream())) {
writer.Write (paramData);
}
GetResponse (request);
Он также терпит неудачу, если я изменил «UseHttpGet = false» в ScriptMethod.
Почему вы используете устаревшие классические веб-службы ASMX? Почему не WCF или WebAPI? также при выполнении POST, что вы публикуете? Проверяли ли вы, что говорят журналы ошибок о внутренней ошибке сервера? Скорее всего, данные, которые вы отправляете, являются недопустимыми или недействительными. –
https: //bugzilla.xamarin. com/show_bug.cgi? id = 34011 Источник доступен, и в последнее время большое количество исходного источника MS было втянуто, разблокировано, отлаживается и выдает запрос на перенос ... В личной заметке я согласен с @Ahmedilyas, go WCF/WebApi ... – SushiHangover
500 означает «проверить журналы, чтобы найти реальная ошибка « – Jason