Force WCF to call a method on every request before

2019-03-25 19:39发布

问题:

I have a RESTful WCF service with many different functions. For each function I need to call an authentication method that I have written. I can manually call this method on every request but I was looking for a way to force the WCF engine to call this method before these functions are entered. Does anyone know if this is possible?

Cheers

回答1:

You could use the "Custom Behavior" approach.

You would need to write a Class that implements IDispatchMessageInspector. The following MSDN magazine article gives a nice explanation of this: Extending WCF with Custom Behaviors (link points to Wayback Machine cached copy; downloads likely don't work).



回答2:

To force WCF REST Service to first call a method especially if it's for authorization customize/override CheckAccessCore method of System.ServiceModel.ServiceAuthorizationManager refer: http://msdn.microsoft.com/en-us/library/ms731774(v=vs.110).aspx



回答3:

If it's for authorization, can't you use the built in services?

For instance, there is the PrincipalPermission attribute. Does that help in your case?



回答4:

You could think about creating a WCF routing service. You would call a fixed endpoint - your authentication method - and then from there on, route your calls to the actual methods, based on some indication in the request.

For .NET 4, the Routing Service functionality will be included into WCF out of the box.

What I don't know is how that all matches REST, though.



回答5:

I came across this post, while searching for the same thing.None of the answer's were simple/quick solution so if you just want a function to be called before every method then you can do what i just did:

I created a zero argument constructor:

public class myService : ImyService 
{
    myService ()
    {
        ConnectToDatabAse();
        FunctionYouWantToCallBeforeEveryMethodCall(); 
        //Add here more
    }
}