Javascript 使用jQuery调用WCF服务
我有两个项目,我需要从中调用WCF服务。 我在从其中一个呼叫服务时遇到问题。 因此,我做了一个简单的服务,它在两个项目中都是相同的,叫做Test1。 SVC、ISVC和Web.Config文件是相同的。 任何其他的想法都可能影响,并且是为什么一个项目正在工作文件而另一个返回错误请求的原因。 我正在Visual studio 2012中工作。 以下是我的代码: SVC文件:Javascript 使用jQuery调用WCF服务,javascript,jquery,wcf,Javascript,Jquery,Wcf,我有两个项目,我需要从中调用WCF服务。 我在从其中一个呼叫服务时遇到问题。 因此,我做了一个简单的服务,它在两个项目中都是相同的,叫做Test1。 SVC、ISVC和Web.Config文件是相同的。 任何其他的想法都可能影响,并且是为什么一个项目正在工作文件而另一个返回错误请求的原因。 我正在Visual studio 2012中工作。 以下是我的代码: SVC文件: namespace Proj1.Web { [ServiceBehavior(InstanceContextMode
namespace Proj1.Web
{
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Proj1SVC : IProj1SVC
{
public string Test1()
{
return "Project 1";
}
}
}
ISVC文件:
namespace Proj1.Web
{
[ServiceContract]
public interface IProj1SVC
{
[OperationContract]
string Test1();
}
}
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="Proj1dbConnectionString" connectionString="Data Source=Proj1Comp\SQLEXPRESS;Initial Catalog=Proj1dbKK;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<roleManager enabled="true"/>
<compilation debug="true" targetFramework="4.0">
</compilation>
<!--
The <authentication> section enables configuration
of the security authentication mode used by
ASP.NET to identify an incoming user.
-->
<!-- <authentication mode="Windows"/> -->
<authentication mode="Forms">
<!-- The name, protection, and path attributes must match
exactly in each Web.config file. -->
<forms loginUrl="login.aspx" name=".ASPXFORMSAUTH" protection="All" path="/" domain="kk.Proj1.com" timeout="600"/>
</authentication>
<!-- Validation and decryption keys must exactly match and cannot
be set to "AutoGenerate". The validation and decryption
algorithms must also be the same. -->
<machineKey validationKey="SomeValidationKeyInHex" decryptionKey="SomeDecryptionKeyInHex" validation="SAA1"/>
<authorization>
<allow roles="administrators"/>
<allow users="?" />
</authorization>
<!--
The <customErrors> section enables configuration
of what to do if/when an unhandled error occurs
during the execution of a request. Specifically,
it enables developers to configure html error pages
to be displayed in place of a error stack trace.
<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>
-->
<pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>
</system.web>
<!-- Added for server side authentication data to be available in the WCF service -->
<!-- STX -->
<system.web.extensions>
<scripting>
<webServices>
<authenticationService enabled="true" requireSSL="false"/>
</webServices>
</scripting>
</system.web.extensions>
<!-- ETX -->
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true"/>
<diagnostics>
<messageLogging
logEntireMessage="true"
logMalformedMessages="false"
logMessagesAtServiceLevel="true"
logMessagesAtTransportLevel="false"
maxMessagesToLog="3000"
maxSizeOfMessageToLog="2000"/>
</diagnostics>
</system.serviceModel>
</configuration>
您需要在服务契约文件中为每个方法或操作指定操作级别的属性。要做到这一点,请使用WebInvoke装饰该方法,它将服务操作标记为响应HTTP请求而不是GET的操作。因此,合同文件中的操作级别代码如下:
[OperationContract]
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.Wrapped,
ResponseFormat = WebMessageFormat.Json)]
string Test1(string Id);
您需要更改Visual Studio在Web.Config文件中为WCF服务创建的默认配置,以便它与jQuery客户端代码发送的HTTP协议请求一起工作
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="EndpBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="ServiceBehavior" name="Service">
<endpoint address="" binding="webHttpBinding"
contract="IService" behaviorConfiguration="EndpBehavior"/>
</service>
</services>
</system.serviceModel>
任何异常或错误?我收到错误400:请求错误。[WebInvokeMethod=POST,BodyStyle=WebMessageBodyStyle.Wrapped,ResponseFormat=WebMessageFormat.Json]不是必需的,因为这是默认设置。My web.config已被更改为使用JQUERY发送的HTTP POST请求查看我的代码。我的JQUERY代码与您发布的代码相同。由于我写的代码与我发布的代码在一个项目中有效,但在另一个项目中不起作用,因此我假设一定有其他因素影响它。请检查两个ur配置文件是否相同这些文件是否相同
function CallService() {
$.ajax({
type: Type, //GET or POST or PUT or DELETE verb
url: Url, // Location of the service
data: Data, //Data sent to server
contentType: ContentType, // content type sent to server
dataType: DataType, //Expected data format from server
processdata: ProcessData, //True or False
success: function(msg) {//On Successfull service call
ServiceSucceeded(msg);
},
error: ServiceFailed// When Service call fails
});
}
function ServiceFailed(result) {
alert('Service call failed: ' + result.status + '' + result.statusText);
Type = null;
varUrl = null;
Data = null;
ContentType = null;
DataType = null;
ProcessData = null;
}