如果我尝试使用 jQuery 或通过浏览器访问方法,我会得到 404。我的配置如下所示:
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="RegistrationBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="RegistrationEndpointBehavior">
<enableWebScript/>
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
<services>
<service name="Corp.EmployeeService" behaviorConfiguration="RegistrationBehavior">
<endpoint address="" binding="webHttpBinding" contract="Corp.IEmployeeService" behaviorConfiguration="RegistrationEndpointBehavior" />
</service>
</services>
</system.serviceModel>
我相信这与配置有关,因为我的方法装饰有 OperationContract 和 WebInvoke 属性。
我的界面(为发布而简化)类似于以下内容:
namespace Corp
{
[ServiceContract]
public interface IEmployeeService
{
[OperationContract]
[WebInvoke(ResponseFormat = WebMessageFormat.Json, Method = "POST")]
int Register(string username);
}
}
在服务类本身上,我使用以下属性对其进行了修饰:
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class EmployeeService : IEmployeeService
正如我所说,我尝试使用http://localhost/EmployeeService.svc/Register或使用 jQuery 来访问服务,如下所示:
$.ajax({
cache: false,
async: true,
type: "POST",
dataType: "json",
url: "http://localhost/EmployeeService.svc/Register",
data: '{"username":"test"}',
contentType: "application/json;charset=utf-8",
success: function (msg) {
var status = msg.RegisterResult;
if (status == 1) {
alert('Success');
} else {
alert('Failure');
}
},
error: function (msg) {
alert('Exception - ' + msg);
}
});
两者都返回 404。
由于我在共享托管公司托管此服务,因此我在 ServiceFactory 上创建了我的服务,如下所示:
public class IisServiceHostFactory : ServiceHostFactory
{
protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
{
var newAddress = baseAddresses[0];
if (!newAddress.AbsoluteUri.Contains("http://www."))
newAddress = new Uri(newAddress.AbsoluteUri.Replace("http://", "http://www."));
var webServiceHost = new IisServiceHost(serviceType, newAddress);
return webServiceHost;
}
}
public class IisServiceHost : ServiceHost
{
public IisServiceHost(Type serviceType, params Uri[] baseAddresses): base(serviceType, baseAddresses) { }
}
尝试从 jQuery 中点击它时正在发生 POST。404 响应(来自为测试而简化的不同示例服务)如下所示:
此异常的文本为:HTTP 404。您正在查找的资源(或其依赖项之一)可能已被删除、名称已更改或暂时不可用。请查看以下 URL 并确保其拼写正确。