我在您的代码中看到多个问题:
405 表示方法不允许 - 这可能意味着您将数据发布到错误的资源。您确定您的地址正确吗?如何公开服务?是吗.svc
文件或ServiceRoute
?如果是.svc
文件地址将是UserService.svc/UserService/ValidateUser
- UserService.svc 因为这是您的服务的入口点(如果您正在使用
ServiceRoute
你可以重新定义这个
- UserService 因为您在端点配置中定义此相对地址
- ValidateUser 因为这是您操作的默认入口点
现在你的 JSON 请求和你的方法签名都是完全错误的。服务合约中的方法签名必须是单个 JSON 对象 = 它必须是单个数据合约,例如:
[DataContract]
public class UserData
{
[DataMember]
public string UserName { get; set; }
[DataMember]
public string Password { get; set; }
}
操作签名将是:
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare)]
[OperationContract]
ServiceObject ValidateUser(UserData userData);
JSON 请求中没有包装器元素,因此您必须使用Bare
。此外,也不需要设置响应格式,因为您将在端点级别设置它(顺便说一句,如果不这样做,您还必须设置请求格式)。
一旦为请求定义了数据契约,您必须正确定义 ajax 请求本身:
$.ajax({
type: 'POST',
url: "UserService.svc/UserService/ValidateUser",
data: '{"UserName":"newuser","Password":"pwd"}',
contentType: "application/json; charset=utf-8",
success: function (msg) {
alert(msg);
},
error: function (xhr, ajaxOptions, thrownError) {
alert('error');
}
});
JSON 对象是字符串!以及它的所有成员!
最后将您的配置修改为:
<system.serviceModel>
<services>
<service name="UserService.UserService">
<endpoint address="UserService" kind="webHttpEndpoint" contract="UserService.IUserService" />
</service>
</services>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
<standardEndpoints>
<webHttpEndpoint>
<standardEndpoint helpEnabled="true" automaticFormatSelectionEnabled="true" />
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>
如果你想使用standardEndpoint
你必须使用kind
在端点定义中,您不需要指定行为(它是标准端点的一部分)。此外,您没有使用跨域调用,因此您不需要启用它们,也不需要默认格式,因为它会自动解析。