目标:公开一个简单的WCF服务,该服务将参数作为用户名的字符串,并查看它是否已存在。此服务将在我正在处理的网站的注册页面上使用,因此当用户输入用户名时,它会自动检查是否已被删除。
我实际上已经使用了这个功能,但我必须为WCF服务启用crossDomainScripting。我的问题是“为什么?”
代码!
我的WCF服务托管在我的MVC3网站中(我最初将它放在一个单独的网站中,但要删除任何和所有关于跨网站scriptiong的问题,我将其移到本地。)
WCF服务的接口
[ServiceContract]
public interface IMembershipServices
{
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json,
UriTemplate = "IsUsernameAvailable/{username}",
BodyStyle = WebMessageBodyStyle.Bare)]
MembershipUserAvailability IsUsernameAvailable(string username);
[OperationContract]
[WebGet(UriTemplate = "helloto/{name}", ResponseFormat = WebMessageFormat.Json)]
string Hello(string name);
}
实现:
[AspNetCompatibilityRequirements(RequirementsMode
= AspNetCompatibilityRequirementsMode.Allowed)]
public class MembershipServices : IMembershipServices
{
#region IMembershipServices Members
public string Hello(string name)
{
return String.Format("Hello:{0}", name);
}
public MembershipUserAvailability IsUsernameAvailable(string username)
{
if (String.IsNullOrWhiteSpace(username))
{
throw new ArgumentException(username);
}
MembershipUser membershipUser = Membership.GetUser(username, false);
var membershipUserAvailability = new MembershipUserAvailability
{
UserName = username,
IsAvailable = membershipUser == null ? true : false
};
return membershipUserAvailability;
}
#endregion
}
Web.config
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
<services>
<!-- This section is optional with the default configuration
model introduced in .NET Framework 4 -->
<service name="MedicalPracticeWeb.Services.MembershipServices" behaviorConfiguration="MembershipServicesBehaviors">
<!-- This endpoint is exposed at the base address provided by host: http://localhost/servicemodelsamples/service.svc -->
<endpoint address="" binding="webHttpBinding" bindingConfiguration="webHttpBindingJsonP" contract="MedicalPracticeWeb.Services.IMembershipServices" behaviorConfiguration="EndpBehavior" />
<!-- The mex endpoint is exposed at http://localhost/servicemodelsamples/service.svc/mex -->
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="MembershipServicesBehaviors">
<!-- Add the following element to your service behavior configuration. -->
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="EndpBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
<bindings>
<webHttpBinding>
<binding name="webHttpBindingJsonP" crossDomainScriptAccessEnabled="true"></binding>
</webHttpBinding>
</bindings>
</system.serviceModel>
Jquery给imlement打电话:
$(document).ready(function () {
var usernameTextbox = $('#username');
var usernameUnavailableRow = $('#usernameUnavailableRow');
var availabilityMessage = $('#availabilityMessage');
usernameTextbox.blur(function () {
if ($(this).val()) {
$.getJSON('/Services/MembershipServiceHost.svc/IsUsernameAvailable/' + escape($(this).val()), function (results) {
if (results.IsAvailable) {
if (usernameUnavailableRow.is(':visible')) {
availabilityMessage.html('This username is available.');
availabilityMessage.addClass('usernameAvailable');
availabilityMessage.removeClass('usernameTaken');
}
}
else {
usernameUnavailableRow.show();
availabilityMessage.html('This username is already taken!');
availabilityMessage.addClass('usernameTaken');
availabilityMessage.removeClass('usernameAvailable');
}
});
}
});
});
现在这一切都很棒。我可以在注册表单的文本框中输入用户名,当我离开该字段时,onBlur事件将触发并调用WCF服务按预期返回结果...但仅如果我有crossDomainScriptAccessEnabled =“true “在我的web.config中。这让我很困惑。也许是缺乏对JSON和JSONP的理解(完全可能。我对使用JSON相当新)但是由于服务托管在同一个域中,为什么我需要这个集合?
我看了一下Fiddler发送的内容:
GET /Services/MembershipServiceHost.svc/IsUsernameAvailable/Tim?callback=jQuery1510988704698288691_1302393437642&_=1302393485350 HTTP / 1.1
我在JQuery文档中提到了回调参数。
http://api.jquery.com/jQuery.getJSON/
如果网址包含字符串“callback =?” (或类似的,由服务器端API定义),请求被视为JSONP。有关更多详细信息,请参阅$ .ajax()中有关jsonp数据类型的讨论。
这是否意味着成功回调的简单行为将迫使GetJSON使用JSONP?
任何意见都赞赏。
答案 0 :(得分:0)
这是否意味着简单的行为 成功回调会 强制GetJSON使用JSONP?
简单的答案是肯定的。
如果您添加参数或将类型设置为jsonp,jQuery将自动为您完成所有艰苦的工作。您还需要您的服务足够智能,以便在将数据发送给您之前将数据包装在函数调用中 - 但.net如果给出参数,则执行此操作。
关于如何通过jQuery使用jsonp,还有很多关于SO的答案。