WCF JSON调用中出现错误

本文关键字:错误 JSON 调用 WCF | 更新日期: 2023-09-27 17:57:36

无论我做什么,我都会在jQueryAjax调用中出错。你能弄清楚我在这里缺了什么吗?

这是我的界面IShow

[ServiceContract]
public interface IShow
{
    [OperationContract]
    string getShow(int _showID);

}

这是我的

    [DataContract]
    public class Show 
    {
        private string _title, _description;
        private DateTime _showDate;
        private int _showID;
        [DataMember]
        public string Title
        {
            get { return _title; }
            set { _title = value; }
        }
        [DataMember]
        public string Description
        {
            get { return _description; }
            set { _description = value; }
        }
        [DataMember]
        public DateTime ShowDate
        {
            get
            {
                return _showDate;
            }
            set { _showDate = value; }
        }
        [DataMember]
        public int ShowID { get { return _showID; } set { _showID = value; } }
}

我的服务名为sShow.svc

  [AspNetCompatibilityRequirements(
        RequirementsMode
       = AspNetCompatibilityRequirementsMode.Allowed)]
    public class sShows : IShow
    {
        [WebInvoke(Method = "POST",
                   BodyStyle = WebMessageBodyStyle.WrappedRequest,
                   ResponseFormat = WebMessageFormat.Json,
                    RequestFormat = WebMessageFormat.Json
                    )]
        public string getShow(int _showID)
        {
            MySqlConnection Conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["CS1"].ConnectionString);
            MySqlCommand cmd = new MySqlCommand();
            cmd.Connection = Conn;
            cmd.CommandType = System.Data.CommandType.Text;
            cmd.CommandText = " SELECT        s.master_id, m.showname, m.showinfo, MIN(CONCAT(s.show_date, ' ', s.show_time)) AS first_show_date, MAX(CONCAT(s.show_date, ' ', s.show_time)) AS last_show_date  FROM            shows s LEFT OUTER JOIN                          master m ON s.master_id = m.master_id  WHERE        (s.wt_offsale = '') AND (s.master_id =  @mid)  GROUP BY s.master_id    ORDER BY s.show_date, s.show_time";
            cmd.Parameters.AddWithValue("@mid", _showID.ToString());
            MySqlDataAdapter da = new MySqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            try
            {
                Conn.Open();
                da.Fill(dt);
                Show sh = null;
                if (dt.Rows.Count > 0)
                {
                    sh = new Show
                    {
                        Title = dt.Rows[0].ItemArray[1].ToString(),
                        Description = dt.Rows[0].ItemArray[2].ToString()
                    };
                }
               // return sh;
                return JsonConvert.SerializeObject(sh, Formatting.Indented);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                Conn.Close();
                dt.Dispose();
                da.Dispose();
            }
        }
    }

最后这是我的web.config(在服务项目中)

      <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
      <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
      <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
      <serviceDebug includeExceptionDetailInFaults="true"/>
    </behavior>
  </serviceBehaviors>
  <endpointBehaviors>
    <behavior name="WebBehaviour">
      <!--<enableWebScript/>-->
      <webHttp defaultOutgoingResponseFormat="Json"/>
      <!--<webHttp/>-->
    </behavior>
  </endpointBehaviors>
</behaviors>

<protocolMapping>
    <add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>    

这是我的Ajax呼叫

   jQuery.ajax({
            type: "POST",
            url: "http://localhost:10677/sShows.svc/Web/getShow",
            data: "{_showID: 288}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            processData: true,
            success: function (result) {
                alert(result.d.Title);
            },
            error: function (result) {
                 alert(result.statusText);
                console.log("Service = " + result.d);
            }
        });

无论我做什么,我都会收到客户端上的"错误"警报。你能检查一下到底是什么问题吗???

感谢

更新这是我从小提琴手那里得到的

    OPTIONS http://localhost:10677/sShows.svc/Web/getShow HTTP/1.1
Host: localhost:10677
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: http://localhost:2299
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36
Access-Control-Request-Headers: accept, content-type
Accept: */*
DNT: 1
Referer: http://localhost:2299/SimiArts/events.aspx
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8,ur;q=0.6

HTTP/1.1 405 Method Not Allowed
Cache-Control: private
Allow: POST
Content-Length: 1565
Content-Type: text/html; charset=UTF-8
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?QzpcVXNlcnNcQXRoYXJBbmlzXERvY3VtZW50c1xNRUdBXFBQSCBKb2JzXFNoYXVuXFdjZlNlcnZpY2UxXHNTaG93cy5zdmNcV2ViXGdldFNob3c=?=
X-Powered-By: ASP.NET
Date: Tue, 08 Apr 2014 16:12:24 GMT
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>Service</title>
    <style>BODY { color: #000000; background-color: white; font-family: Verdana; margin-left: 0px; margin-top: 0px; } #content { margin-left: 30px; font-size: .70em; padding-bottom: 2em; } A:link { color: #336699; font-weight: bold; text-decoration: underline; } A:visited { color: #6699cc; font-weight: bold; text-decoration: underline; } A:active { color: #336699; font-weight: bold; text-decoration: underline; } .heading1 { background-color: #003366; border-bottom: #336699 6px solid; color: #ffffff; font-family: Tahoma; font-size: 26px; font-weight: normal;margin: 0em 0em 10px -20px; padding-bottom: 8px; padding-left: 30px;padding-top: 16px;} pre { font-size:small; background-color: #e5e5cc; padding: 5px; font-family: Courier New; margin-top: 0px; border: 1px #f0f0e0 solid; white-space: pre-wrap; white-space: -pre-wrap; word-wrap: break-word; } table { border-collapse: collapse; border-spacing: 0px; font-family: Verdana;} table th { border-right: 2px white solid; border-bottom: 2px white solid; font-weight: bold; background-color: #cecf9c;} table td { border-right: 2px white solid; border-bottom: 2px white solid; background-color: #e5e5cc;}</style>
  </head>
  <body>
    <div id="content">
      <p class="heading1">Service</p>
      <p>Method not allowed.</p>
    </div>
  </body>
</html>

WCF JSON调用中出现错误

"{_showID: 288}"不是有效的JSON。"{'"_showID'": 288}"可能就是你想要的。或者,最好创建一个普通对象,让jQuery进行JSON序列化。

data: { _showId: 288 },

OPTIONS调用是由于跨站点脚本调用引起的。使网站和服务位于同一主机和端口上,或者使用JSONP回调,如jQuery$.ajax()、$.post-setting"OPTIONS";正如Firefox中的REQUEST_METHOD所建议的那样。