繁体   English   中英

415不支持从$ .ajax调用WCF服务的媒体类型

[英]415 Unsupported Media Type Calling WCF Service from $.ajax

我试图从ASPX页面调用WCF Web服务,如下所示:

var payload = {
    applicationKey: 40868578
};

$.ajax({
    url: "/Services/AjaxSupportService.svc/ReNotify",
    type: "POST",
    data: JSON.stringify(payload),
    contentType: "application/json",
    dataType: "json"
});

这样做会导致Web服务器返回错误415 Unsupported Media Type 我确定这是WCF服务的配置问题,其定义如下:

[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json)]
void ReNotify(int applicationKey);

web.config文件中没有任何条目,因此假定该服务使用默认配置。

我不是这方面的专家,实际上我有同样的问题(由于另一个原因)。 但是,WCF服务似乎并不固有地支持AJAX,因此您必须在web.config文件中具有以下代码才能启用它。

<system.serviceModel>
    <behaviors>
        <endpointBehaviors>
            <behavior name="NAMESPACE.AjaxAspNetAjaxBehavior">
                <enableWebScript />
            </behavior>
        </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
        multipleSiteBindingsEnabled="true" />
    <services>
        <service name="NAMESPACE.SERVICECLASS">
            <endpoint address="" behaviorConfiguration="NAMESPACE.AjaxAspNetAjaxBehavior"
                binding="webHttpBinding" contract="NAMESPACE.SERVICECLASS" />
        </service>
    </services>
</system.serviceModel>

然后在服务类中

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;

namespace NAMESPACE
{
    [ServiceBehavior(IncludeExceptionDetailInFaults = true)]
    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class SERVICECLASS
    {
        // To use HTTP GET, add [WebGet] attribute. (Default ResponseFormat is WebMessageFormat.Json)
        // To create an operation that returns XML,
        //     add [WebGet(ResponseFormat=WebMessageFormat.Xml)],
        //     and include the following line in the operation body:
        //         WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
        [OperationContract]
        public string DoWork()
        {
            // Add your operation implementation here
            return "Success";
        }

        // Add more operations here and mark them with [OperationContract]
    }
}

这是当我添加启用了AJAX的WCF服务时VS 2012生成的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM