Json 为WCF REST中的每个请求自动调用该方法
我有一个WCF Rest服务,在调用服务方法时,我们需要验证许可证密钥,它是每个请求消息的一部分(请求和响应消息将是JSON格式)。为了验证许可证密钥,我们需要为每个请求调用单独的方法,该方法将包含如下逻辑:如果输入请求包含无效的许可证密钥,那么我们需要以JSON格式向客户端发送错误消息,如“invalid license key”。 为此,我们在WCF Rest中是否有任何方法自动为每个请求调用此方法,而不是为每个请求显式调用Json 为WCF REST中的每个请求自动调用该方法,json,wcf,rest,wcf-rest,Json,Wcf,Rest,Wcf Rest,我有一个WCF Rest服务,在调用服务方法时,我们需要验证许可证密钥,它是每个请求消息的一部分(请求和响应消息将是JSON格式)。为了验证许可证密钥,我们需要为每个请求调用单独的方法,该方法将包含如下逻辑:如果输入请求包含无效的许可证密钥,那么我们需要以JSON格式向客户端发送错误消息,如“invalid license key”。 为此,我们在WCF Rest中是否有任何方法自动为每个请求调用此方法,而不是为每个请求显式调用 注意:-许可证密钥将在服务Web.Config文件中可用。您可以使
注意:-许可证密钥将在服务Web.Config文件中可用。您可以使用消息检查器,该检查器将为服务的每个请求调用。下面的代码显示了此类检查器的一个实现
public class StackOverflow_25380450
{
[ServiceContract]
public class Service
{
[WebGet]
public int Add(int x, int y)
{
return x + y;
}
}
public class MyInspector : IDispatchMessageInspector, IEndpointBehavior
{
public const string LicenseHeaderName = "X-License";
public const string ExpectedLicense = "abcdef";
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
{
HttpRequestMessageProperty reqProp = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name];
var license = reqProp.Headers[LicenseHeaderName];
if (license != ExpectedLicense)
{
throw new WebFaultException<string>("License required", HttpStatusCode.Forbidden);
}
return null;
}
public void BeforeSendReply(ref Message reply, object correlationState)
{
}
public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{
}
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
}
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
endpointDispatcher.DispatchRuntime.MessageInspectors.Add(this);
}
public void Validate(ServiceEndpoint endpoint)
{
}
}
public static string SendGet(string uri, Dictionary<string, string> headers)
{
string responseBody = null;
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uri);
req.Method = "GET";
if (headers != null)
{
foreach (string headerName in headers.Keys)
{
switch (headerName)
{
case "Accept":
req.Accept = headers[headerName];
break;
default:
req.Headers[headerName] = headers[headerName];
break;
}
}
}
HttpWebResponse resp;
try
{
resp = (HttpWebResponse)req.GetResponse();
}
catch (WebException e)
{
resp = (HttpWebResponse)e.Response;
}
if (resp == null)
{
responseBody = null;
Console.WriteLine("Response is null");
}
else
{
Console.WriteLine("HTTP/{0} {1} {2}", resp.ProtocolVersion, (int)resp.StatusCode, resp.StatusDescription);
foreach (string headerName in resp.Headers.AllKeys)
{
Console.WriteLine("{0}: {1}", headerName, resp.Headers[headerName]);
}
Console.WriteLine();
Stream respStream = resp.GetResponseStream();
if (respStream != null)
{
responseBody = new StreamReader(respStream).ReadToEnd();
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine("HttpWebResponse.GetResponseStream returned null");
}
}
Console.WriteLine();
Console.WriteLine(" *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* ");
Console.WriteLine();
return responseBody;
}
public static void Test()
{
string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
var endpoint = host.AddServiceEndpoint(typeof(Service), new WebHttpBinding(), "");
endpoint.Behaviors.Add(new WebHttpBehavior { AutomaticFormatSelectionEnabled = true });
endpoint.Behaviors.Add(new MyInspector());
host.Open();
Console.WriteLine("Host opened");
Console.WriteLine("No license:");
Dictionary<string, string> headers = new Dictionary<string, string>
{
{ "Accept", "application/json" }
};
SendGet(baseAddress + "/Add?x=6&y=8", headers);
Console.WriteLine("Incorrect license:");
headers.Add(MyInspector.LicenseHeaderName, "incorrect");
SendGet(baseAddress + "/Add?x=6&y=8", headers);
headers[MyInspector.LicenseHeaderName] = MyInspector.ExpectedLicense;
SendGet(baseAddress + "/Add?x=6&y=8", headers);
Console.Write("Press ENTER to close the host");
Console.ReadLine();
host.Close();
}
}
公共类StackOverflow_25380450
{
[服务合同]
公务舱服务
{
[WebGet]
公共整数相加(整数x,整数y)
{
返回x+y;
}
}
公共类MyInspector:IDispatchMessageInspector、IEndpointBehavior
{
public const string LicenseHeaderName=“X-License”;
public const字符串ExpectedLicense=“abcdef”;
接收请求后的公共对象(ref消息请求、IClientChannel通道、InstanceContext InstanceContext)
{
HttpRequestMessageProperty reqProp=(HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name];
var license=需求标题[LicenseHeaderName];
如果(许可证!=预期许可证)
{
抛出新的WebFaultException(“需要许可证”,HttpStatusCode.Forbidden);
}
返回null;
}
SendReply之前的公共无效(参考消息回复,对象关联状态)
{
}
public void AddBindingParameters(ServiceEndpoint端点、BindingParameterCollection bindingParameters)
{
}
public void ApplyClientBehavior(ServiceEndpoint端点、ClientRuntime ClientRuntime)
{
}
公共无效ApplyDispatchBehavior(ServiceEndpoint端点、EndpointDispatcher端点Dispatcher)
{
endpointDispatcher.DispatcheRuntime.MessageInspectors.Add(此);
}
公共void验证(ServiceEndpoint)
{
}
}
公共静态字符串SendGet(字符串uri、字典头)
{
字符串responseBody=null;
HttpWebRequest req=(HttpWebRequest)HttpWebRequest.Create(uri);
req.Method=“GET”;
如果(标题!=null)
{
foreach(headers.Keys中的字符串headerName)
{
开关(头部名称)
{
案例“接受”:
请求接受=标题[标题名称];
打破
违约:
请求标头[标头名称]=标头[标头名称];
打破
}
}
}
HttpWebResponse resp;
尝试
{
resp=(HttpWebResponse)req.GetResponse();
}
捕获(WebE例外)
{
resp=(HttpWebResponse)e.Response;
}
如果(resp==null)
{
responseBody=null;
Console.WriteLine(“响应为空”);
}
其他的
{
WriteLine(“HTTP/{0}{1}{2}”,resp.ProtocolVersion,(int)resp.StatusCode,resp.StatusDescription);
foreach(分别在header.allkey中的字符串headerName)
{
WriteLine(“{0}:{1}”,headerName,resp.header[headerName]);
}
Console.WriteLine();
Stream respStream=resp.GetResponseStream();
if(respStream!=null)
{
responseBody=新的StreamReader(respStream).ReadToEnd();
控制台写入线(应答器体);
}
其他的
{
WriteLine(“HttpWebResponse.GetResponseStream返回null”);
}
}
Console.WriteLine();
Console.WriteLine(“*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*”;
Console.WriteLine();
返回响应体;
}
公共静态无效测试()
{
string baseAddress=“http://“+Environment.MachineName+”:8000/服务”;
ServiceHost主机=新ServiceHost(类型(服务),新Uri(基地址));
var endpoint=host.AddServiceEndpoint(typeof(Service),new WebHttpBinding(),“”);
Add(新的WebHttpBehavior{automaticFormatSelectEnabled=true});
添加(新的MyInspector());
host.Open();
Console.WriteLine(“主机已打开”);
Console.WriteLine(“无许可证:”);
字典头=新字典
{
{“接受”、“应用程序/json”}
};
SendGet(基本地址+“/Add?x=6&y=8”,标题);
Console.WriteLine(“不正确的许可证:”);
headers.Add(MyInspector.LicenseHeaderName,“不正确”);
SendGet(基本地址+“/Add?x=6&y=8”,标题);
标题[MyInspector.LicenseHeaderName]=MyInspector.ExpectedLicense;
SendGet(基本地址+“/Add?x=6&y=8”,标题);
控制台。写入(“按ENTER键关闭主机”);
Console.ReadLine();
host.Close();
}
}
有关检查员的更多信息,请访问。这正是我所期望的。谢谢分享。保持你的代码为基础,我已经提到。这是非常有用的。最后,我很高兴获得可执行代码。需要一个小说明,如何从正文而不是标题检索许可证密钥?如果密钥在正文中,则需要读取传递的
请求
参数