我有.NET Web服务,它应该将结果作为JSON返回,但是它将它作为XML返回?这是我的代码。
[WebService(Namespace = "http://tempuri.org/MyService")]
[ScriptService]
public class MyService : System.Web.Services.WebService
{
[WebMethod, ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<MyData> GetMyData(string dataFilter, string param)
{
if (dataFilter.ToLower() == "filterValue")
return getData(param);
return null;
}
}
public class MyData
{
public string id { get; set; }
public string name { get; set; }
protected internal MyData() { }
}
这是web.config
<system.web>
<compilation debug="true" targetFramework="4.0"/>
<httpRuntime/>
<customErrors mode="Off"/>
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
<pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>
修改 Web服务仅在传递参数中的数字时才能正常工作,但在参数内传递字符时会返回内部服务器错误。我感到困惑:O
答案 0 :(得分:1)
尝试此代码可能对您有所帮助。安装 Newtonsoft.Json 包
<强>代码强>
public class HelloWorldData
{
public String Message;
}
[WebMethod]
public void Select()
{
JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Clear();
Context.Response.ContentType = "application/json";
HelloWorldData data = new HelloWorldData();
string sql = "exec YOUR_SP_NAME";
SqlDataAdapter da = new SqlDataAdapter(sql, System.Configuration.ConfigurationManager.AppSettings["BB_CONSTR"]);
DataSet ds = new DataSet();
da.Fill(ds);
Context.Response.Write(JsonConvert.SerializeObject(ds, Newtonsoft.Json.Formatting.Indented));
}