Search code examples
c#asp.net-mvcwpfentity-frameworkwcf-data-services

Entity Framework data service request headers for mvc


We have an Entity framework web service, that needs authentication to access. This authentication needs to happen every time a request is sent.

The system im editing has it working perfectly for a WPF application by overriding the OnSendingRequest event of the entity container from the mainWindow.xaml.cs file. then adding the authorization to the header. And i found a resource that tells me to do something similar, but i dont know how this works in a ASP.NET MVC project, since the resource seems to only give an example of how to do it for a single request, in WPF. How to: Set Headers in the Client Request (WCF Data Services

I need to make this same authentication header for the connection of the mvc project, for every request.


Solution

  • Incase someone else finds this useful, i solved the problem by accident.

    I made a static class, and a static method, that can be called from any page in the project. with this code:

    var serviceUri = new Uri(WebConfigurationManager.AppSettings["DataServiceUri"]);
    myService result = new myService(serviceUri);
    
    result.SendingRequest += new EventHandler<SendingRequestEventArgs>((s, e) =>
    {
        string authenticationString = applicationName + " " + applicationId;
        e.RequestHeaders.Add("Authorization", authenticationString);
    });
    
    return result;
    

    This both creates and returns the instance of the service, to use in the calling method, and also automatically creates the Authorization and executes it.

    This hasto be done on each of the controllers that communicates with the service. Enjoy.