我有 ASMX 网络服务,我想以 JSON 格式返回结果。当我的 web 方法没有参数时,它工作正常。
[WebService(Namespace = "http://www.arslanonline.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class AuthService : System.Web.Services.WebService {
public AuthService () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
[System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
public string Authenticate(string username, string password, string appId)
{
return ToJson("Hello World");
}
public static string ToJson(object obj)
{
return JsonConvert.SerializeObject(obj);
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string Test()
{
return ToJson("Hello World");
}
当我以这种方式调用我的测试 Web 方法时,它工作正常
string url= "http://localhost:45548/Moves/AuthService.asmx/Test";
string dataToPost= "";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/json;";
request.BeginGetRequestStream(new AsyncCallback(DoHTTPPostRequestReady), new HttpWebRequestData<string>()
{
Request = request,
Data = dataToPost
});
并返回我的 JSON 结果。但是对于我的第二种方法 Authenticate ,它采用了我要求的一些参数
string url= "http://localhost:45548/Moves/AuthService.asmx/Authenticate";
string dataToPost= "username=ABC&password=123&appid=1";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/json;";
request.BeginGetRequestStream(new AsyncCallback(DoHTTPPostRequestReady), new HttpWebRequestData<string>()
{
Request = request,
Data = dataToPost
});
它给了我Not Found Error
但是当我改变为request.ContentType = "application/x-www-form-urlencoded"
; 它工作正常,并以 XML 格式返回我的结果,但不是 JSON 格式。为什么会发生这种情况可以请任何人告诉我代码中的故障在哪里。