从jQuery调用ASP.NET 4.0 WCF服务会产生400 Bad Request

时间:2022-08-24 22:12:38

I know it seems this question has been posted many times, but I've read nearly all of them (an most of the tutorials on the internet), and I still can't grasp what I'm doing wrong.

我知道似乎这个问题已被多次发布,但我已经阅读了几乎所有这些问题(互联网上的大部分教程),我仍然无法理解我做错了什么。

I tried to implement in a web site we're developing a WCF web service to be consumed by a jQuery script, but I keep getting 400 Bad Request when doing the AJAX request, and I'm starting to loose hope.

我试图在一个网站上实现我们正在开发一个由jQuery脚本使用的WCF Web服务,但在执行AJAX请求时我一直收到400 Bad Request,我开始失去希望。

Please note that I'm new to WCF, and I've formed myself only through online tutorials, so it's entirely possible I overlook or majorly screwed up something.

请注意,我是WCF的新手,我只是通过在线教程形成自己,所以我完全有可能忽略或主要搞砸了。

Questions I tried but didn't help:

我尝试但没有帮助的问题:

External resources I read to no avail:

我读到的外部资源无济于事:

I also tried creating a new solution, with only a page and the service, to rule out interferences, but I still have the same problem. Here you can find the code:

我还尝试创建一个新的解决方案,只有一个页面和服务,以排除干扰,但我仍然有同样的问题。在这里你可以找到代码:

IService.cs

IService.cs

namespace WebService
{
    using System;
    using System.ServiceModel;
    using System.ServiceModel.Web;

    [ServiceContract(Name = "Service", Namespace = "WebService")]
    public interface IService
    {
        [OperationContract]
        [WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped, Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        String Test();
    }
}

Service.svc.cs

Service.svc.cs

namespace WebService
{
    using System;

    public class Service : IService
    {
        public String Test()
        {
            return "Hello, world.";
        }
    }
}

Default.aspx

Default.aspx的

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebService.Default" %>
<!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 runat="server">
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            $(document).ready(function () {
                $("#doAjax").click(function (event) {
                    event.preventDefault();
                    jQuery.ajax({
                        contentType: "application/json"
                        , dataType: "text"
                        , error: function (jqXHR, textStatus, errorThrown) {
                            console.group("AJAX error:");
                            console.debug(jqXHR);
                            console.debug(textStatus);
                            console.groupEnd();
                        }
                        , processData: false
                        , success: function (data, textStatus, jqXHR) {
                            console.group("AJAX success:");
                            console.debug(data);
                            console.debug(textStatus);
                            console.debug(jqXHR);
                            console.groupEnd();
                        }
                        , type: "post"
                        , url: "/Service.svc/Test"
                    });
                });
            });
        </script>
        <title>WebService</title>
    </head>
    <body>
        <form runat="server">
            <h1><%= this.Page.Title %></h1>
            <p><input id="doAjax" type="button" value="Run" /></p>
        </form>
    </body>
</html>

Web.config

Web.config文件

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.web>
        <compilation debug="true" targetFramework="4.0" />
    </system.web>
    <system.serviceModel>
        <bindings />
        <client />
        <behaviors>
            <endpointBehaviors>
                <behavior name="Behavior">
                    <webHttp />
                </behavior>
            </endpointBehaviors>
            <serviceBehaviors>
                <behavior name="">
                    <serviceMetadata httpGetEnabled="true" />
                    <serviceDebug includeExceptionDetailInFaults="false" />
                </behavior>
            </serviceBehaviors>
        </behaviors>
        <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
        <services>
            <service name="Service">
                <endpoint behaviorConfiguration="Behavior" binding="webHttpBinding" contract="WebService.IService" />
            </service>
        </services>
    </system.serviceModel>
</configuration>

2 个解决方案

#1


2  

The service name must be fully qualified. Try: <service name="WebService.Service">

服务名称必须完全限定。尝试:

#2


1  

Hey! I was having this same problem (.....again) but finally figured it out and got it working properly.

嘿!我有同样的问题(.....再次)但最终想出来并让它正常工作。

Now this is my own example, but because it worked for me, hopefully it will work for you too... The key line that I was forgetting was in my $ajax command:

现在这是我自己的例子,但因为它对我有用,希望它对你也有用...我忘记的关键是在我的$ ajax命令中:

contentType: "application/json; charset=utf-8"

Good luck :) I spent half a day on this issue.

祝你好运:)我在这个问题上花了半天时间。

interface:

接口:

[OperationContract]
[WebInvoke(ResponseFormat = WebMessageFormat.Json)]
int CreateMilestone(Milestone Input);

Class:

类:

[DataContract]
public class Milestone
{
    [DataMember]
    public string Name { get; set; }
    [DataMember]
    public string Date { get; set; }
    [DataMember]
    public int Risk { get; set; }
    [DataMember]
    public int Complexity { get; set; }
}

the method:

方法:

   public int CreateMilestone(Milestone Input)
    {
        return 0;
    }

the jquery:

jquery:

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

    if ($.trim($("#txtName").val()) == "") {
        $("#dName").effect("highlight", 500);
    }
    else {

        var date = $("#txtDate").datepicker("getDate");
        var data = {
            Name: $("#txtName").val(),
            Date: (date.getMonth() + 1) + "-" + date.getDate() + "-" + date.getFullYear(),
            Risk: parseInt($("#sRisk").text()),
                Complexity: parseInt($("#sComplexity").text())
            };
            var jsondata = JSON.stringify(data);
            $.ajax({
                type: "POST",
                async: false,
                url: 'Services/ProjectService.svc/CreateMilestone',
                contentType: "application/json; charset=utf-8",
                data: jsondata,
                dataType: "json",
                success: function (msg) {
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    //                        alert(XMLHttpRequest.status);
                    //                        alert(XMLHttpRequest.responseText);
                }
            });
        }
    });

#1


2  

The service name must be fully qualified. Try: <service name="WebService.Service">

服务名称必须完全限定。尝试:

#2


1  

Hey! I was having this same problem (.....again) but finally figured it out and got it working properly.

嘿!我有同样的问题(.....再次)但最终想出来并让它正常工作。

Now this is my own example, but because it worked for me, hopefully it will work for you too... The key line that I was forgetting was in my $ajax command:

现在这是我自己的例子,但因为它对我有用,希望它对你也有用...我忘记的关键是在我的$ ajax命令中:

contentType: "application/json; charset=utf-8"

Good luck :) I spent half a day on this issue.

祝你好运:)我在这个问题上花了半天时间。

interface:

接口:

[OperationContract]
[WebInvoke(ResponseFormat = WebMessageFormat.Json)]
int CreateMilestone(Milestone Input);

Class:

类:

[DataContract]
public class Milestone
{
    [DataMember]
    public string Name { get; set; }
    [DataMember]
    public string Date { get; set; }
    [DataMember]
    public int Risk { get; set; }
    [DataMember]
    public int Complexity { get; set; }
}

the method:

方法:

   public int CreateMilestone(Milestone Input)
    {
        return 0;
    }

the jquery:

jquery:

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

    if ($.trim($("#txtName").val()) == "") {
        $("#dName").effect("highlight", 500);
    }
    else {

        var date = $("#txtDate").datepicker("getDate");
        var data = {
            Name: $("#txtName").val(),
            Date: (date.getMonth() + 1) + "-" + date.getDate() + "-" + date.getFullYear(),
            Risk: parseInt($("#sRisk").text()),
                Complexity: parseInt($("#sComplexity").text())
            };
            var jsondata = JSON.stringify(data);
            $.ajax({
                type: "POST",
                async: false,
                url: 'Services/ProjectService.svc/CreateMilestone',
                contentType: "application/json; charset=utf-8",
                data: jsondata,
                dataType: "json",
                success: function (msg) {
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    //                        alert(XMLHttpRequest.status);
                    //                        alert(XMLHttpRequest.responseText);
                }
            });
        }
    });