简体   繁体   中英

jQuery Ajax Post to WCF returning “Bad Request”

I can't seem to quite get this.

I have a WCF service like this;

    [OperationContract]
    [WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped, Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    bool Test();

Then the implementation;

    public bool Test()
    {
        return true;
    }

Then my jQuery;

                jQuery.support.cors = true;
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8", 
                    dataType: "json",
                    url: "http://localhost:8732/Design_Time_Addresses/MyService/Service/mex/Test",
                    timeout: 2000,
                    success: function (data) {
                        alert(9);
                    },
                    error: function (xhr, status, error) {
                        alert(status);
                        alert(error);
                    }
                });

Every time I call this I get "Bad Request". If I change the URL to this say;

http://localhost:8732/Design_Time_Addresses/MyService/Service/mex/Tesdt

i get the error "Unknown" so i think it's finding my service.

You have ResponseFormat = WebMessageFormat.Json in your server method.

Yet in your AJAX call the dataType (that you are expecting back from the server) is text .

TLDR:

Change dataType: "text" ----> dataType: "json"

You usually shouldn't send the request to the "mex" endpoint, unless you configured your web endpoint address to that. If your webHttpBinding / webHttpBehavior endpoint is at http://localhost:8732/Design_Time_Addresses/MyService/Service , then the URI in your service should be just that.

$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    url: "http://localhost:8732/Design_Time_Addresses/MyService/Service/Test",
    timeout: 2000,
    success: function (data) {
        alert(9);
    },
    error: function (xhr, status, error) {
        alert(status);
        alert(error);
    }
});

Check that address, and if it doesn't work, please post your web.config and your global.asax.cs (if you're defining any routes)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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