在C#中使用JSON WCF服务
我想从我页面后面的代码中使用我的json wcf web服务:
Default.aspx.cs
string result = url + "/ExecuteAction?callback=?"; var httpWebRequest = (HttpWebRequest)WebRequest.Create(result); httpWebRequest.ContentType = "text/json"; httpWebRequest.Method = "POST"; using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { string json = new JavaScriptSerializer().Serialize(new { action = "HelloWorld", args = "Nabila" }); streamWriter.Write(json); streamWriter.Flush(); streamWriter.Close(); } var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { var response = streamReader.ReadToEnd(); }
我的服务:
[OperationContract] [WebGet(ResponseFormat = WebMessageFormat.Json)] public string ExecuteAction(string action, string args) { String JSONResult = String.Empty; MethodInfo action = services.GetMethod(action, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static); JSONResult =(String)action.Invoke(null, new object[] { args }); }
services.cs
public static string HelloWorld(string msg) { return JsonConvert.SerializeObject("Hello World"+msg); }
我得到以下exception:
从c#使用json wcf Web服务远程服务器返回错误:(405)Method Not Allowed。 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender,EventArgs e)
注意:当我使用javascript使用我的Web服务时它可以工作:
$.ajax({ type: "POST", crossDomain: true, timeout: 10000, url: getUrl() + "ExecuteAction?callback=?", data: { action: "HelloWorld", args: 'test'}, contentType: "application/json; charset=utf-8", dataType: "jsonp" }).done(function (msg) {alert("success");}).fail(function () {alert("error");});
请你帮助我好吗。
谢谢。
纳比拉。
我观察到你的问题是DataType 。 在Javascript调用中,您将datType设置为jsonp
dataType: "jsonp"
在Default.aspx.cs文件中,您将发送普通的JSON。 JSON和JSONP之间存在差异 。
尝试在Deafult.aspx.cs文件中更改JSON类型,然后运行。 这可能会解决您的问题。
编辑:将您的合同更改为:
[OperationContract] [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "json")] public string ExecuteAction(JSONRequest request) { String JSONResult = String.Empty; MethodInfo action = services.GetMethod(action, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static); JSONResult =(String)action.Invoke(null, new object[] { args }); } [DataContract] public class JSONRequest { [DataMember] public string Action {get; set;} [DataMember] public string Args {get; set;} }