【问题标题】:GET error when trying to post to WCF Web Service via AJAX尝试通过 AJAX 发布到 WCF Web 服务时出现 GET 错误
【发布时间】:2016-03-03 06:45:56
【问题描述】:

我有一个 mvc 项目,我试图发布到我通过 Web 表单和 AJAX 调用创建的 WCF 服务。当它访问 WebService 时我收到一个错误,它说的是 GET。

这是它的图像:

AJAX 的重要部分如下所示:

    var songRequest = {
        Title: 'New Slang',
        Artist: 'The Shins',
        Genre: 'Indie',
        Difficulty: 'Easy',
        id: 11
    };

    $(document).ready(function () {

        $("#createSong").on("click", "#saveSong", function () {

            $.ajax({
                url: 'http://localhost:17476/SongRESTService.svc/json/PostJson/',
                dataType: 'jsonp',
                contentType: 'application/json',
                data: JSON.stringify(songRequest),
                method: "POST"
            }).done(function (response, b, c) {
                console.log(response, b, c);

            }).error(function (xhr) {
                console.log(xhr);
                alert("There was an error saving the song. Please try again.");
            });

        });
    });

通常会从表单生成数据,但我只是为了测试目的对其进行了硬编码。

webservice 部分如下所示:

    [OperationContract]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]

    [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json,
                       BodyStyle = WebMessageBodyStyle.Bare,
                       UriTemplate = "json/PostJson/")]
    String PostJson();

有什么想法吗?

编辑:网络选项卡错误:

【问题讨论】:

  • 我们需要查看实际错误,进入 Chrome 中的网络选项卡并查看请求/响应。
  • 您是否在服务端启用了JSONPCORS?您似乎没有给出错误消息。您似乎违反了此 AJAX 请求的同源策略。
  • DavidG,我添加了图片,但我认为它没有提供更多信息
  • 达林,我不这么认为。我已经用谷歌搜索了很多,但还没有找到在服务端启用它的位置。
  • 是的,它显示 HTTP 405,这意味着该服务不接受您正在使用的 HTTP 方法。

标签: c# jquery ajax web-services wcf


【解决方案1】:

您已指定dataType: 'jsonp' 并尝试发出没有任何意义的 POST 请求,因为 JSONP 仅适用于 GET 请求(至少在 jQuery 的实现中)。如果您需要使用 POST 动词,您可以考虑使用 CORS。为此,您可以通过将以下内容添加到您的 Global.asax 来在您的服务器上全局启用 CORS:

protected void Application_BeginRequest()
{
    if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
    {
        if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST, PUT, DELETE, GET, OPTIONS");
            HttpContext.Current.Response.End();
        }
    }
}

现在从您的 AJAX 调用中删除这个 dataType: 'jsonp'

如果您使用 IIS,另一种可能性是将以下内容添加到您的 web.config:

<system.webServer>
    <httpProtocol>
        <customHeaders>
            <add name="Access-Control-Allow-Origin" value="*" />
            <add name="Access-Control-Allow-Methods" value="POST, PUT, DELETE, GET, OPTIONS" />
            <add name="Access-Control-Allow-Credentials" value="true" />
        </customHeaders>
    </httpProtocol>
</system.webServer>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-05
    • 2016-03-23
    • 2010-10-10
    • 1970-01-01
    • 2018-10-03
    • 1970-01-01
    • 2012-04-30
    • 1970-01-01
    相关资源
    最近更新 更多