Ajax调用从asp.net的MVC到WCF [英] ajax call to wcf from asp.net mvc

查看:173
本文介绍了Ajax调用从asp.net的MVC到WCF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个应用程序。首先是WCF服务,第二个是asp.net MVC 3应用程序。
在WCF应用程序我有一个接口:

I have two apps. The first is WCF Service, the second is asp.net MVC 3 app.
In the WCF app I have a interface:

    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        string HelloWorld(string personName);
    }

和一个类:

public class Service1 : IService1
    {
        public string HelloWorld(string personName)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            return serializer.Serialize("Hello " + personName);
        }
    }

现在,在asp.net mvc的应用程序,我想通过Ajax调用这个方法:

Now, in the asp.net mvc app I want call this method via Ajax:

<script type="text/javascript">
    var personName = "John";
    var dataIn = '{' + '"input":"' + personName + '"}';
    $.ajax({
        url: "http://localhost:7215/Service1.svc/HelloWorld",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: dataIn,
        dataType: "json",
        success: function (data) {
            var object = JSON.parse(data.d);
            if (object.Error == '') {
                $("#response").html(object);
            }
        },
        error: function (error) {
            alert("Error: " + error);
        }
    });
    </script>

但在萤火虫我得到错误: 400错误的请求
如何正确地调用的HelloWorld 的方法? 谢谢你。

But in the Firebug I get error: 400 Bad Request.
How to call HelloWorld method properly? Thanks.

推荐答案

所以,你想消耗的 WCF服务的距离的的JavaScript 的?

So you are trying to consume a WCF service from JavaScript?

我看到的第一个问题是,你的服务还没有准备好从JavaScript消耗:(。你必须做以下修改。

The first problem I see is, your service is not yet ready to be consumed from JavaScript :(. You have to make the following changes..

  1. 配置服务1 类与 AspNetCompatibilityRequirements 的行为。

标记的服务方法的HelloWorld WebGet 属性界面。 [你需要参照 System.SericeModel.Web 组装]

Mark the service method HelloWorld in interface with WebGet attribute. [You need reference to System.SericeModel.Web assembly]

使得两更改后..

[ServiceContract]
public interface IService1
{
  [OperationContract]
  [WebGet(ResponseFormat = WebMessageFormat.Json)]
  string HelloWorld(string personName);
}

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1 : IService1
{
  public string HelloWorld(string personName)
  {
    JavaScriptSerializer serializer = new JavaScriptSerializer();

    // you are not returning data in proper JSON format, wrap the text in
    // an anonymous object before serializing.
    return serializer.Serialize(new { text = "Hello " + personName });
  }
}

下一页。

  1. 配置的WebHttpBinding 的服务(请确保您更改服务及合约名字!)。

  1. Configure webHttpBinding for the service (Make sure you change the service and contract names!).

<system.serviceModel>
  <behaviors>
    <endpointBehaviors>
      <behavior name="webHttpBehavior">
        <webHttp />
      </behavior>
    </endpointBehaviors>
  </behaviors>
  <bindings>
    <webHttpBinding>
      <binding name="webHttpBindingWithJsonP" />
    </webHttpBinding>
  </bindings>
  <services>
    <service name="MvcApplication3.Service1">
      <endpoint address="" binding="webHttpBinding"
                bindingConfiguration="webHttpBindingWithJsonP"
                contract="MvcApplication3.IService1"
                behaviorConfiguration="webHttpBehavior"/>
    </service>
  </services>
</system.serviceModel>

所以,现在的服务是准备好了!

So now the service is ready!

让我们做客户端的修改

  <script type="text/javascript">
      var personName = "John";
      var dataIn = '{' + '"input":"' + personName + '"}';
      $.ajax({
         url: "http://localhost:50623/Service1.svc/HelloWorld",
         type: "GET",
         contentType: "application/json; charset=utf-8",
         data: dataIn,
         dataType: "json",
         success: function (data) {
           var jsonData = JSON.parse(data);
           $("#response").html(jsonData.text);
         },
         error: function (error) {
           alert("Error: " + error);
         }
      });
   </script>

直到现在我认为,无论是WCF服务和MVC应用程序在同一域中运行。

Till now I've assumed that both the WCF service and the MVC app are running in the same domain.

但如果不是这样,那么你将格特一个 405 (不允许的方法)的错误,由于跨域屏障

But if that's not the case then you will gete a 405(Method Not Allowed) error due to CROSS-DOMAIN BARRIER.

有不同的方法来解决这个问题!

There are different ways to overcome this problem!

1。使用JSONP

在这种情况下,你必须在 crossDomainScriptAccessEnabled 属性设置为的结合,你必须做出JSONP从jQuery的电话。

In this case you have to set the crossDomainScriptAccessEnabled property to true in the binding and you have to make JSONP calls from jQuery.

<binding name="webHttpBindingWithJsonP" crossDomainScriptAccessEnabled="true" />

然后修改的dataType JSON JSONP $。阿贾克斯方法。

  <script type="text/javascript">
      var personName = "John";
      var dataIn = '{' + '"input":"' + personName + '"}';
      $.ajax({
         ...
         dataType: "jsonp",
         ...
      });
   </script>

2。采用CORS

请参照本..

http://www.w3.org/TR/cors/

<一个href="https://developer.mozilla.org/en/http_access_control">https://developer.mozilla.org/en/http_access_control

这篇关于Ajax调用从asp.net的MVC到WCF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆