【问题标题】:Bad Request Call WCF Service Jquery Ajax错误请求调用 WCF 服务 Jquery Ajax
【发布时间】:2014-03-04 07:24:15
【问题描述】:

我正在尝试为 Jquery Ajax 获取 JSON 的 WCF 服务,但该方法甚至没有被启动,现在返回错误 Bad Request。

下面是调用服务、服务接口、服务类、服务Web.config、Global.asax服务的Java脚本代码。

详细信息如果我访问 $.getJSON 的 GetData 方法有效,但在 $.Ajax 无效。

已经使用 AddStudant 方法无法以某种方式工作。

谁能帮忙告诉我怎么了?

JavaScript

$("#bt").click(function () {

var url = "http://domain.net/Service1.svc/AddStudant";变量数据 = {“ID”:1,“名称”:“爱立信阿尔维斯”};变量 jdata = {}; jdata.student = 数据;

callAjax(url, 'json', 'POST', 功能(结果){ 警报(结果); }, JSON.stringify(jdata) ); });

函数 callAjax(ajaxUrl, ajaxDataType, ajaxType, funcSucess, 数据值){

    $.ajax({
        url: ajaxUrl,
        dataType: ajaxDataType,
        type: ajaxType,
        data: dataValues,
        processdata: true,
        contentType: "application/json;charset-uf8"
    })
        .done(function (data) {
            funcSucess(data);
        })
        .always(function (data) {

        }).fail(function (xhr, status, errorThrown) {
            alert(xhr.responseText);
        });
}

界面

[ServiceContract]
    public interface IService1
    {
        [OperationContract]
        [WebInvoke(Method = "GET",
        BodyStyle = WebMessageBodyStyle.WrappedRequest,
        ResponseFormat = WebMessageFormat.Json)]
        Student GetData(int id);

        [OperationContract]
        [WebInvoke(Method = "POST",
        BodyStyle = WebMessageBodyStyle.WrappedRequest,
        ResponseFormat = WebMessageFormat.Json,
        RequestFormat = WebMessageFormat.Json)]
        Student AddStudant(Student student);

    }

[DataContract]
    public class Student
    {
        [DataMember]
        public int ID { get; set; }
        [DataMember]
        public string Name { get; set; }
    }

服务类

[AspNetCompatibilityRequirements(RequirementsMode
    = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Service1 : IService1
    {
        [WebInvoke(Method = "GET",
        BodyStyle = WebMessageBodyStyle.WrappedRequest,
        ResponseFormat = WebMessageFormat.Json)]
        public Student GetData(int id)
        {
            return new Student() { ID = id, Name ="Ericsson Alves" };
        }

        [WebInvoke(Method = "POST",
        BodyStyle = WebMessageBodyStyle.WrappedRequest,
        ResponseFormat = WebMessageFormat.Json,
        RequestFormat = WebMessageFormat.Json)]
        public Student AddStudant(Student student)
        {
            return new Student() { ID = student.ID , Name ="Ericsson Alves" };
        }
    }

Web.config 服务

<?xml version="1.0"?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <system.serviceModel>

    <bindings>
      <webHttpBinding>
        <binding name="WebHttpBdg" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" />
      </webHttpBinding>
    </bindings>

    <behaviors>
      <serviceBehaviors>
        <behavior name="BehaviorDefault">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="AJAXWCFServiceAspNetAjaxBehavior">
          <webHttp defaultOutgoingResponseFormat="Json" automaticFormatSelectionEnabled="true" />
        </behavior>
      </endpointBehaviors>
    </behaviors>

    <services>
      <service name="TestWCFJsonAjax.Service.Service1" behaviorConfiguration="BehaviorDefault">
        <endpoint address="" binding="webHttpBinding" bindingConfiguration="WebHttpBdg"
                  behaviorConfiguration="AJAXWCFServiceAspNetAjaxBehavior"
          name="Service1" contract="TestWCFJsonAjax.Service.IService1" />
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
    </services>

    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
      multipleSiteBindingsEnabled="true" />

    <standardEndpoints>
      <webHttpEndpoint>
        <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true" crossDomainScriptAccessEnabled="true" />
      </webHttpEndpoint>
    </standardEndpoints>

  </system.serviceModel>

  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <directoryBrowse enabled="true"/>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
        <!--<add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS" />-->
      </customHeaders>
    </httpProtocol>
  </system.webServer>

</configuration>

Global.asax 服务

public class Global : System.Web.HttpApplication
    {

        protected void Application_Start(object sender, EventArgs e)
        {
            RouteTable.Routes.Add(new ServiceRoute("", new WebServiceHostFactory(), typeof(Service1)));
        }
        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            //HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            //HttpContext.Current.Response.Cache.SetNoStore();

            //EnableCrossDmainAjaxCall();
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                HttpContext.Current.Response.End();
            }
        }
    }

【问题讨论】:

    标签: jquery ajax json wcf


    【解决方案1】:

    尝试发送data 而不是jdata,我想您需要像{ "ID": 1, "Name": "Ericsson Alves" } 一样发送对象,而不是像您当前正在发送的那样在另一个对象中发送它{student: { "ID": 1, "Name": "Ericsson Alves" }}

    【讨论】:

      【解决方案2】:

      在您的 ajax 请求中将 contentType 设置为 text/plain

      【讨论】:

      • 请解释为什么这是一个解决方案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-11
      • 1970-01-01
      • 1970-01-01
      • 2013-06-22
      • 1970-01-01
      • 2012-04-23
      • 2013-09-23
      相关资源
      最近更新 更多