简体   繁体   English

使用 WCF Rest 错误跨域调用

[英]Error cross domain call using WCF Rest

I'm trying to make a WCF service with CORS calls, so far, I have my server with the classes indicated here: http://enable-cors.org/server_wcf.html我正在尝试使用 CORS 调用创建 WCF 服务,到目前为止,我的服务器带有此处指示的类: http : //enable-cors.org/server_wcf.html

I was able to make a call with a jQuery ajax call using the verb GET without any parameters, the problem comes when I try to pass parameters to my request, here's my code:我能够使用不带任何参数的动词 GET 使用 jQuery ajax 调用进行调用,当我尝试将参数传递给我的请求时出现问题,这是我的代码:

Interface markup:接口标记:

[OperationContract]
[WebInvoke(Method = "*",
           RequestFormat = WebMessageFormat.Json,
           ResponseFormat = WebMessageFormat.Json,
           BodyStyle = WebMessageBodyStyle.WrappedRequest)]
string GetData(TestClass value);

Method markup:方法标记:

public string GetData(TestClass value)
{
     return value.Id.ToString();
}

js markup: js 标记:

var value = { 
    Id : "2", 
    Name: "qwe" 
};

$.ajax({
    url: "http://localhost:38733/Service1.svc/GetData",
    type: "POST",
    contentType: "application/json",
    dataType: "json",
    data: JSON.stringify({ value: value }),
    success: function(result) {
        console.log(result);
    },
    error: function(jqXHR, textStatus, errorThrown) {
        console.log(jqXHR);
    }
});

But if I debug, I always get null, meaning that the parameter is not being passes to the method, I also got POST http://localhost:38733/Service1.svc/GetData 400 (Bad Request) on Chrome console.但是如果我调试,我总是得到空值,这意味着参数没有传递给方法,我还在 Chrome 控制台上得到POST http://localhost:38733/Service1.svc/GetData 400 (Bad Request)

What am I doing wrong?我究竟做错了什么?

UPDATE更新

Web.config markup: Web.config 标记:

<behavior name="jsonBehavior">
    <webHttp />
    <crossOriginResourceSharingBehavior />
</behavior>

<extensions>
  <behaviorExtensions>
    <add name="crossOriginResourceSharingBehavior" 
         type="WCFSecureService.EnableCrossOriginResourceSharingBehavior, WCFSecureService, Version=1.0.0.0, Culture=neutral" />
  </behaviorExtensions>
</extensions>

<services>
  <service name="WCFSecureService.Service1">
    <endpoint address="" 
              binding="webHttpBinding" 
              behaviorConfiguration="jsonBehavior" 
              contract="WCFSecureService.IService1" />
  </service>
</services>

On the Google Chrome Console I'm getting the following:在 Google Chrome 控制台上,我得到以下信息:

OPTIONS http://localhost:38733/Service1.svc/GetData?value=5

UPDATE更新

It works if I make a request to a method without any parameters如果我向没有任何参数的方法发出请求,它会起作用

UPDATE更新

Fiddler 2 is showing me this, so I don't know what I'm doing wrong... Fiddler 2 正在向我展示这个,所以我不知道我做错了什么......

请求错误

UPDATE更新

TestClass markup:测试类标记:

[DataContract]
public class TestClass
{
    private int id;
    private string name;

    [DataMember]
    public string Name
    {
        get { return name; }
        set { name = value; }
    }

    [DataMember]
    public int Id
    {
        get { return id; }
        set { id = value; }
    }        
}

UPDATE更新

If I use JSON.stringify({ value: value }) and BodyStyle = WebMessageBodyStyle.Bare I reach the server, but I got all properties with 0, check the next image:如果我使用JSON.stringify({ value: value })BodyStyle = WebMessageBodyStyle.Bare我到达服务器,但我得到的所有属性都是 0,检查下一张图片:

调试时出错

In your service contract you might want to put an optional WebGet directive.在您的服务合同中,您可能想要放置一个可选的WebGet指令。

[WebGet(UriTemplate = "GetData/{value}")]
string GetData(int value);

Another thing to look for is that you have a json behavior defined for your enpoint in the web.config.要寻找的另一件事是您在 web.config 中为您的端点定义了一个json行为。

<endpointBehaviors>
    <behavior name="jsonBehavior">
        <webHttp defaultOutgoingResponseFormat="Json"/>
    </behavior>
    <behavior name="xmlBehavior">
      <webHttp defaultOutgoingResponseFormat="Xml"/>
    </behavior>
</endpointBehaviors>

NOTE: If you are using behaviors and then you need to specify the format in the following manner注意:如果您正在使用行为,那么您需要按以下方式指定格式

http://localhost:38733/Service1.svc/json/GetData/5

or或者

http://localhost:38733/Service1.svc/xml/GetData/5

Also, could you try this js instead:另外,你可以试试这个js吗:

var _data= {
    value:5
};

$.ajax({
    ...
    data: _data,
    success: function(data) {
        console.log(data);
    },
    error: function(jqXHR, textStatus, errorThrown) {
        console.log(jqXHR);
    }
});

Or conversely:或者相反:

$.ajax({
    url: "http://localhost:38733/Service1.svc/json/GetData/5",
});

I've found a solution for my case.我已经为我的案例找到了解决方案。 At the end this was a test, so I'm gonna be using more that just one parameter so this is what I've learn:最后这是一个测试,所以我将使用更多的参数,所以这就是我学到的:

  • For more than one parameter, the request has to be wrapped, so, the annotation of the contract for WebInvoke has to be BodyStyle = WebMessageBodyStyle.WrappedRequest .对于多个参数,请求必须被包装,因此, WebInvoke的合同注释必须是BodyStyle = WebMessageBodyStyle.WrappedRequest
  • On the client side, for just one parameter, using JSON.stringify(value) it's ok, but for more than one, you have to be more specific, for example:在客户端,对于一个参数,使用JSON.stringify(value)问题,但是对于多个参数,您必须更具体,例如:

     data: JSON.stringify({ value: value, text: "any text" });
  • On the link I provide on my question, I have to included two clases CustomHeaderMessageInspector and EnableCrossOriginResourceSharingBehavior , it seems that they are not longer needed if you can make use of a global.asax file, you just have to add the following code to Application_BeginRequest :在我提供的关于我的问题的链接上,我必须包含两个类CustomHeaderMessageInspectorEnableCrossOriginResourceSharingBehavior ,如果您可以使用global.asax文件,似乎不再需要它们,您只需将以下代码添加到Application_BeginRequest

     HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*"); if (HttpContext.Current.Request.HttpMethod == "OPTIONS") { HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST, PUT, DELETE, GET"); HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept"); HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000"); HttpContext.Current.Response.End(); }

And my web.config end it up like this:我的web.config最终是这样的:

<bindings>
  <webHttpBinding>
    <binding name="Binding" crossDomainScriptAccessEnabled="true">
      <security mode="Transport">
        <transport clientCredentialType="None" />
      </security>
    </binding>
    <binding name="corsBinding" crossDomainScriptAccessEnabled="true" />
  </webHttpBinding>
</bindings>

<services>
  <service name="WCFSecureService.Service1" behaviorConfiguration="ServiceBehaviour">
    <endpoint address="bs" binding="basicHttpBinding" contract="WCFSecureService.IService1" />
    <endpoint address="" 
              binding="webHttpBinding"
              bindingConfiguration="corsBinding"
              behaviorConfiguration="jsonBehavior"
              contract="WCFSecureService.IService1" />
  </service>
</services>

<behaviors>
  <serviceBehaviors>
    <behavior name="ServiceBehaviour">
      <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="true" />
    </behavior>
    <behavior name="jsonBehavior">
      <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="true" />
    </behavior>
  </serviceBehaviors>

  <endpointBehaviors>        
    <behavior name="jsonBehavior">
      <webHttp helpEnabled="true" />
    </behavior>
  </endpointBehaviors>
</behaviors>

Thanks for your helps and I hope it helps someone else out there.感谢您的帮助,我希望它可以帮助其他人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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