从 jQuery 调用一个简单的 WCF 服务
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7621528/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
calling a simple WCF Service from jQuery
提问by webdad3
I have a very simple WCF Service called pilltrkr.svc. I'm trying to call this service from jQuery via the following code:
我有一个非常简单的 WCF 服务,叫做 pilltrkr.svc。我正在尝试通过以下代码从 jQuery 调用此服务:
var jsondata = JSON.stringify();
$.ajax({
type: "POST",
async: false,
url: './pilltrakr.svc/DoWork/',
contentType: "application/json; charset=utf-8",
data: jsondata,
dataType: "json",
success: function (msg) {
alert(msg);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
// alert(XMLHttpRequest.status);
// alert(XMLHttpRequest.responseText);
}
});
I am doing this locally (so using localhost). DoWork just returns a string. When I call this function I get a http://localhost:57400/pilltrakr/pilltrakr.svc/DoWork/ 404 Not Found
我在本地执行此操作(因此使用本地主机)。DoWork 只返回一个字符串。当我调用这个函数时,我得到一个http://localhost:57400/pilltrakr/pilltrakr.svc/DoWork/ 404 Not Found
How do I call my WCF Service? I've tried several different variations (after researching). I was able to call this service using the code behind method (client). I'm sure this is a real easy thing to do. Please advise.
如何调用我的 WCF 服务?我尝试了几种不同的变体(经过研究)。我能够使用隐藏方法(客户端)的代码调用此服务。我相信这是一件非常容易做到的事情。请指教。
More code -
更多代码 -
It seems like every post on Stack includes the interface and the actual class for the service, so I am also putting them here, just in case there is something I'm missing:
似乎 Stack 上的每个帖子都包含该服务的接口和实际类,所以我也将它们放在这里,以防万一我遗漏了什么:
Interface:
界面:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;
using System.Web;
namespace serviceContract
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "Ipilltrakr" in both code and config file together.
[ServiceContract]
public interface Ipilltrakr
{
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
string DoWork();
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
int addUser(string userName, string userPhone, string userEmail, string userPwd, string acctType);
}
}
class:
班级:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using pillboxObjects;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
namespace serviceContract
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "pilltrakr" in code, svc and config file together.
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class pilltrakr : Ipilltrakr
{
string Ipilltrakr.DoWork()
{
return "got here";
}
int Ipilltrakr.addUser(string userName, string userPhone, string userEmail, string userPwd, string acctType)
{
userAccount ua = new userAccount();
int uId;
ua.userName = userName;
ua.userPhone = userPhone;
ua.userEmail = userEmail;
ua.userPwd = userPwd;
ua.userCreateDate = DateTime.Now;
ua.userAccountType = acctType;
uId = ua.add();
return uId;
}
}
}
web config:
网络配置:
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<connectionStrings>
<add name="xxxConnectionString" connectionString="Data Source=xxx;Initial Catalog=xxx;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
</assemblies>
</compilation>
</system.web>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_Ipilltrakr" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
useDefaultWebProxy="true">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:57400/pilltrakr/pilltrakr.svc/pilltrakr"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_Ipilltrakr"
contract="svcPilltrakr.Ipilltrakr" name="BasicHttpBinding_Ipilltrakr" />
</client>
<services>
<service name="serviceContract.pilltrakr" behaviorConfiguration="MyServiceTypeBehaviors">
<endpoint contract="serviceContract.Ipilltrakr" binding="basicHttpBinding" address="pilltrakr" bindingNamespace="serviceContract"/>
<endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="MyServiceTypeBehaviors">
<serviceMetadata httpGetEnabled="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="false" />
</system.serviceModel>
</configuration>
采纳答案by webdad3
I figured out how to finally call my simple WCF service from jQuery. I found some source code after reading this link:
我想出了如何最终从 jQuery 调用我的简单 WCF 服务。阅读此链接后,我找到了一些源代码:
http://www.west-wind.com/weblog/posts/2009/Sep/15/Making-jQuery-calls-to-WCFASMX-with-a-ServiceProxy-Client. This link doesn't provide the source but it was another page that referenced this link.
http://www.west-wind.com/weblog/posts/2009/Sep/15/Making-jQuery-calls-to-WCFASMX-with-a-ServiceProxy-Client。此链接不提供来源,但它是引用此链接的另一个页面。
Anyway, I downloaded the code and started to compare my code versus this working project that was calling a WCF Service via jQuery. What I found was that my web.config file was way too complicated so I shorted that up considerably. Then I also realized that my methods were not public. So I made them public and then after a few more tweaks (i.e. taking out the namespaces) the page started to return the simple string I was trying to return.
无论如何,我下载了代码并开始将我的代码与这个通过 jQuery 调用 WCF 服务的工作项目进行比较。我发现我的 web.config 文件太复杂了,所以我大大缩短了它。然后我也意识到我的方法不是公开的。所以我将它们设为公开,然后经过一些调整(即去掉命名空间),页面开始返回我试图返回的简单字符串。
<system.serviceModel>
<services>
<service name="pilltrakr" behaviorConfiguration="MyServiceTypeBehaviors">
<endpoint address="" behaviorConfiguration="pilltrakrAspNetAjaxBehavior" binding="webHttpBinding" contract="Ipilltrakr"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="MyServiceTypeBehaviors">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="pilltrakrAspNetAjaxBehavior">
<enableWebScript/>
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
</system.serviceModel>
回答by IainJMitchell
回答by patel.milanb
what i found in google, might help you.
我在谷歌上找到的,可能对你有帮助。
$(document).ready(function() {
$("#sayHelloButton").click(function(event){
$.ajax({
type: "POST",
url: "dummyWebsevice.svc/HelloToYou",
data: "{'name': '" + $('#name').val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
AjaxSucceeded(msg);
},
error: AjaxFailed
});
});
});
function AjaxSucceeded(result) {
alert(result.d);
}
function AjaxFailed(result) {
alert(result.status + ' ' + result.statusText);
}
[WebMethod()]
public static string sayHello()
{
return "hello ";
}