大家好我想尝试从javascript函数调用wcf服务由于某种原因asp.net没有识别命名空间并在运行时给我一个错误,任何帮助将非常感谢以下是代码:
默认的aspx页面
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/WeatherService.svc"/>
</Services>
</asp:ScriptManager>
Enter a zipcode:
<input id="zipCodeInput" type="text" />
<br/>
<input id="getForecastButton" type="button" value="Get Forecast" onclick="onGetForecast()"/>
<br/>
<div id="resultsDiv">
</div>
</form>
Javasript
<script language="javascript" type="text/javascript">
function onGetForecast() {
var zip = document.getElementById("zipCodeInput").value;
//alert(zip);
UltimateServices.GetForecast(zip, onGetForecastComplete, onGetForecastError, zip);
}
function onGetForecastComplete(result, userData) {
document.getElementById("resultsDiv").innerHTML = "Weather for " + userData + " is going to be " + result;
}
function onGetForecastError(err) {
alert("There was a error " + err.get_message());
}
</script>
WeatherService.cs文件(代码隐藏)
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;
[ServiceContract(Namespace = "UltimateServices")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class WeatherService
{
private static Random _rand = new Random();
[OperationContract]
public string GetForecast(string zipcode)
{
string forecast = "";
switch(_rand.Next(3))
{
case 0:
forecast = "Sunny and Warm";
break;
case 1:
forecast = "Chilly and overcast";
break;
case 2:
forecast = "Hot and humid";
break;
}
return forecast;
}
// Add more operations here and mark them with [OperationContract]
}
web.config文件
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="WeatherServiceAspNetAjaxBehavior">
<enableWebScript />
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" />
<services>
<service name="WeatherService">
<endpoint address="" behaviorConfiguration="WeatherServiceAspNetAjaxBehavior"
binding="webHttpBinding" contract="WeatherService" />
</service>
</services>
</system.serviceModel>
答案 0 :(得分:1)
这里我使用javascript从WCF调用简单的hello world
Service.cs
using System;
using System.Collections.Generic;
using System.Linq;`
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.ServiceModel.Activation;
//注意:您可以使用“重构”菜单上的“重命名”命令在代码,svc和配置文件中一起更改类名“服务”。
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service : IService
{
[WebGet(ResponseFormat = WebMessageFormat.Json)]
public string helloworld(string name)
{
name = "Hello " + name;
return name;
}
}
的web.config
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
</system.web>
<system.serviceModel>
<services>
<service name="Service" behaviorConfiguration="DefaultBehavior">
<endpoint address="" binding="webHttpBinding" contract="IService" name="RunningBarbus.Services.RunningBarbusService" behaviorConfiguration="AjaxBehavior">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex"/>
</service>
</services>
<bindings>
<webHttpBinding>
<binding crossDomainScriptAccessEnabled="true">
<security mode="None"/>
</binding>
</webHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="DefaultBehavior">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="AjaxBehavior">
<!--<enableWebScript/>-->
<webHttp helpEnabled="true" automaticFormatSelectionEnabled="false" />
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
<standardEndpoints>
<webScriptEndpoint>
<standardEndpoint crossDomainScriptAccessEnabled="true" name="">
</standardEndpoint>
</webScriptEndpoint>
</standardEndpoints>
</system.serviceModel>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="access-control-allow-headers" value="content-type, Accept" />
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS" />
<add name="Access-Control-Max-Age" value="1728000" />
</customHeaders>
</httpProtocol>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
javascript代码
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="jsonp.aspx.cs" Inherits="jsonp" %>
<!DOCTYPE html >
<html>
<head runat="server">
<title></title>
<script src="js/jquery-1.10.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
var name="";
var Type;
var Url = "http://192.168.X.X/WCFjavascript/Service.svc/helloworld?name=world";
var Data;
var ContentType;
var DataType;
var ProcessData;
var method;
//Generic function to call WCF Service
function CallService() {
$.ajax({
type: Type, //GET or POST or PUT or DELETE verb
url: Url, // Location of the service
// data: name, //Data sent to server
contentType: ContentType, // content type sent to server
//data: '[{"name":"' + name + '"}]',
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(xhr) {
alert(xhr.responseText);
if (xhr.responseText) {
var err = xhr.responseText;
if (err)
error(err);
else
error({ Message: "Unknown server error." })
}
return;
}
function ServiceSucceeded(result) {
debugger;
if (DataType == "jsonp") {
alert(result);
resultObject = result.helloworld;
var string = result.name ;
alert(string);
}
}
function helloworld() {
debugger;
var uesrid = "";
Type = "GET";
// Url = "http://192.168.X.X/WCFjavascript/Service.svc/helloworld?'"+uesrid+'"';
Url = Url;
DataType = "jsonp"; ProcessData = false;
method = "helloworld";
CallService();
}
$(document).ready(
function () {
helloworld();
}
);
enter code here
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
答案 1 :(得分:0)
您似乎缺少服务/服务方法的ScriptService / ScriptMethod属性。