Call authenticated web service in asp.net MVC
asp.net-mvc, svcutil.exe, wsdl
Solution
I got a project with the same behavior, a Web Service (asmx) was behind a VPN and they use username/password to access it, but inside the VPN it was ok.
It will be hard to generate the proxy class directly from Visual Studio (maybe lack of support for such scenarios) but the trick is really easy as long as you can see the schema in a browser (the wsdl part).
do this:
- open the `?wsdl` link in a browser, go to `Source Code` mode and copy the entire code to a file in your local computer, let'a assume `c:\temp` and called `service.wsdl`
- copy `svcutil.exe` to `c:\temp` (it's in .NET Framework folder, just search for it)
- open a terminal in `c:\temp` (Shift + Right Click inside the folder and choose Open command window here)
- run the following command: `svcutil service.wsdl /out:proxy.cs /config:proxy.config`
This will generate 2 files, the `proxy.cs` and the `proxy.config`
- `proxy.cs` is your web service wrapper, all you need is to add to your project
- `proxy.config` has the `<system.serviceModel>` that you need to append to your `web.config` file.
Now, all you need to do is follow the generated wrapper and write something like:
// Web Service initialization and authentication
client = new MyNamespace.ServiceSoapClient();
client.ClientCredentials.UserName.UserName = cUser;
client.ClientCredentials.UserName.Password = cPass;
// do something
client.InsertCompetitor(model);
// close connection
if (client != null && client.State == System.ServiceModel.CommunicationState.Opened)
client.Close();
Problem
My problem is in calling authenticated (has username and password) web service (asmx) in ASP.NET MVC I did the following: - I added the web service to the project by adding service reference to the solution Tried to create proxy class of the service by using `wsdl.exe` tool using the following command syntax `wsdl /username:******** /password:************* /domain:********** web service url.asmx?wsdl` but it gave me the following error: There was an error downloading `web service url://???.asmx?wsdl`. The request failed with HTTP status `401: Unauthorized`. I can view the service in browser by giving username and password. When I search for using `svcutil.exe` to create proxy class I found that it can't be used for authenticated web service. I want to ask if there is another way to create proxy class , or if we can call authenticated web service in asp.net mvc application without proxy class.