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

标签 jquery asp.net ajax wcf c#-4.0

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

var payload = {
    applicationKey: 40868578
};

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

这样做会导致网络服务器返回错误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 生成的内容。

关于jquery - 415 不支持的媒体类型从 $.ajax 调用 WCF 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11477420/

相关文章:

javascript - 如何获取剑道网格的滚动位置

asp.net - 如何在 ASP.NET 转发器中对 HTML 进行编码?

javascript - Jquery 欧芹验证不起作用

asp.net - asp :RegularExpressionValidator, 确保字符串中没有逗号

asp.net - 如何在 IIS7 中为 HttpHandler 注册多个路径?

javascript - 未捕获的语法错误 : Unexpected token < ajax call jsonp

php - 如何在ajax过程中显示加载动画和禁用按钮

javascript - Ubergallery 和 ajax

jquery - Twitter bootstrap modal 落后于 iframe

带有 jQ​​uery Validate 插件的 jQuery UI 工具提示