关于如何创建 WCF RESTfull service,请移步
这里。
大家应该都知道,在WCF 世界里, 类似配置一类的东西一般都有两种实现方式 --
1. 纯代码方式
2. 配置文件方式
本文也将要以这两种方式来呈现。
GO!
首先你要实现一个你自己的 ServiceAuthorizationManager
using System.ServiceModel;
using System.ServiceModel.Web;
public class RestAuthorizationManager : ServiceAuthorizationManager
{
protected override bool CheckAccessCore(OperationContext operationContext)
{
return CheckAccessCore(WebOperationContext.Current);
}
}
在 CheckAccessCore 方法中就可以写你自己的验证逻辑了, 甚至可以设置本次请求的 status code
operation.OutgoingResponse.StatusCode =HttpStatusCode.Unauthorized;
接下来就是两种方式的不同之处了
1. 代码方式。
1) 需要额外实现一个自己的 WebServiceHostFactory.
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Activation;
using System.Web;
namespace WCFRestfulService
{
public class SecureWebServiceHostFactory : WebServiceHostFactory
{
protected override System.ServiceModel.ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
{
var host = base.CreateServiceHost(serviceType, baseAddresses);
host.Authorization.ServiceAuthorizationManager = new CertificationAuthorizationManager();
return host;
}
public override System.ServiceModel.ServiceHostBase CreateServiceHost(string constructorString, Uri[] baseAddresses)
{
var host = base.CreateServiceHost(constructorString, baseAddresses);
host.Authorization.ServiceAuthorizationManager = new CertificationAuthorizationManager();
return host;
}
}
}
2) 添加Route 并绑定自己的WebServiceHostFactory.(在Global.asax 文件中)
protected void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.Add(new System.ServiceModel.Activation.ServiceRoute("RestService", new SecureWebServiceHostFactory(),
typeof(RestService)));
}
2. 配置文件方式
添加一个service behavior
<behaviors>
<serviceBehaviors>
<behavior name="RestServiceBehavior">
<serviceMetadata httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceAuthorization
serviceAuthorizationManagerType="{your namespace}.RestAuthorizationManager,{your assemble name}
</behavior>
</serviceBehaviors>
</behaviors>
绑定此service behavior 到 service
<service behaviorConfiguration="RestServiceBehavior"
.....
OK, Done.