문제

I am trying to use CORS on WCF for cross domain calls to the service. I have most of the things working, but when I try to call the function it always gives me a error -HTTP 400 Bad Request

I used Fiddler to capture the error and it says something like this

enter image description here

When I tried to find solutions, I saw people suggesting to use BodyStyle=WebMessageBodyStyle.Bare. I tried that and the service was giving errors because I have more than one parameters.

[OperationContract]
        [WebInvoke(Method = "POST",
                    BodyStyle=WebMessageBodyStyle.Wrapped,
                    RequestFormat=WebMessageFormat.Json,
                    ResponseFormat=WebMessageFormat.Json,
                    UriTemplate = "/GetData")]
        //[WebGet(BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "/GetData/{value}/")]
        string GetData(string value, string val2);

I am not sure how to solve this problem. Any help will be appreciated.

If you need to look at anything more, like my config please let me know and I can share it.

SERVICE CALL:

var datav = "{value : 4, val2 : 5}";
            var datasent = JSON.stringify(datav);
    $.ajax({
            type: "POST",
            dataType: 'json',
            contentType: "application/json",
            data: datasent,
            url: pURL,
            success: function (data) {
            alert('success');
            },
            error: function(xhr, status, error) {
              alert(xhr.responseText);
            }
            });
도움이 되었습니까?

해결책

First of all, it is not recommended to use POST if your Service is just returning data. Use GET instead. But still, if you are going to use POST, then here is the proper method to use it in WCF.

[OperationContract]
[WebInvoke(Method = "POST",
  BodyStyle=WebMessageBodyStyle.Bare,
  RequestFormat=WebMessageFormat.Json,
  ResponseFormat=WebMessageFormat.Json,
  UriTemplate = "/GetData")]    
string GetData(MyValues values);

And here is your MyValues class.

[DataContract]
public class MyValues
{
   [DataMember]
   public string value1{get; set;}

   [DataMember]
   public string value2{get; set;}

   public override string ToString()
   {
      JavaScriptSerializer js = new JavaScriptSerializer(); // Available in   System.Web.Script.Serialization;           
      return js.Serialize(this);
   }
}

Note that I have written, ToString() method in MyValues class. This is because you can get the format of JSON that you will send from JSON call. More details here.

When calling from AJAX, you need to specify charset as well.

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

Check now! Make sure that you are sending right JSON in your request. ToString() method will return you the required JSON format that your service will accept.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top