Getting “Object is read only” error when setting C

2020-06-08 01:40发布

I have a proxy object generated by Visual Studio (client side) named ServerClient. I am attempting to set ClientCredentials.UserName.UserName/Password before opening up a new connection using this code:

InstanceContext context = new InstanceContext(this);

m_client = new ServerClient(context);
m_client.ClientCredentials.UserName.UserName = "Sample";

As soon as the code hits the UserName line it fails with an "Object is read-only" error. I know this can happen if the connection is already open or faulted, but at this point I haven't called context.Open() yet.

I have configured the Bindings (which uses netTcpBinding) to use Message as it's security mode, and MessageClientCredentialType is set to UserName.

Any ideas?

12条回答
倾城 Initia
2楼-- · 2020-06-08 01:43

here is the solution:

using SysSvcmod = System.ServiceModel.Description;

SysSvcmod.ClientCredentials clientCredentials = new SysSvcmod.ClientCredentials();
clientCredentials.UserName.UserName = "user_name";
clientCredentials.UserName.Password = "pass_word";

m_client.ChannelFactory.Endpoint.Behaviors.RemoveAt(1);
m_client.ChannelFactory.Endpoint.Behaviors.Add(clientCredentials);
查看更多
Anthone
3楼-- · 2020-06-08 01:47

I noticed that after creating an instance of the proxy class for the service, I can set the Username and Password once without errors and do a successful call to my webservice. When I then try to set the Username and Password again on the existing instance (unnecessary of course) I get the 'Object is Read-Only' error you mentioned. Setting the values once per instance lifetime worked for me.

查看更多
姐就是有狂的资本
4楼-- · 2020-06-08 01:48

I was facing same problem, my code started working when I changed my code i.e. assigning values to Client credential immediately after initializing Client object.

here is the solution ,

ProductClient Manager = new  ProductClient();    
Manager.ClientCredentials.UserName.UserName = txtUserName.Text;
Manager.ClientCredentials.UserName.Password = txtPassword.Text;
查看更多
虎瘦雄心在
5楼-- · 2020-06-08 01:48

This will not happen if the service reference is added through -> Add service reference ->Advanced->Add Web Reference-> Url/wsdl (local disk file).

查看更多
在下西门庆
6楼-- · 2020-06-08 01:51

It appears that you can only access these properties pretty early in the instanciation cycle. If I override the constructor in the proxy class (ServerClient), I'm able to set these properties:

base.ClientCredentials.UserName.UserName = "Sample";

I'm beginning to appreciate the people who suggest not using the automatically built proxies provided by VS.

查看更多
贼婆χ
7楼-- · 2020-06-08 01:52

A shot in the dark but does netTcpBinding allow username and password validation? Try using application layer (SOAP) security using a http binding

查看更多
登录 后发表回答