gpt4 book ai didi

c# - ASMX 网络服务中的 JSON 结果

转载 作者:太空宇宙 更新时间:2023-11-03 21:45:12 24 4
gpt4 key购买 nike

我有 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"));
}

关于c# - ASMX 网络服务中的 JSON 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17403244/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com