我有 ASMX 网络服务,我想以 JSON 格式返回结果。当我的网络方法没有参数时它工作正常。
[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 格式返回结果。为什么会发生这种情况,任何人都可以告诉我代码中的故障在哪里。
请您参考如下方法:
使用 void 作为方法的返回类型。
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void Test()
{
System.Web.HttpContext.Current.Response.Write(ToJson("Hello World"));
}
