Xamarin Android中MainActivity调用Web Service的两类问题求助
Hey there, let's tackle these two common issues you're facing with calling Web Services in your Xamarin.Android project—they're pretty typical when getting started, so no worries!
Follow these steps to get it sorted:
确认服务引用已正确添加:
First, double-check that you've successfully added the target Web Service via right-clicking your project → Add → Connected Service (or Service Reference). If you haven't done this yet, complete this step first to ensure the proxy classes are generated.导入正确的命名空间:
When adding the service reference, you specified a namespace (e.g.,MyApp.WebServices). You need to import this namespace at the top of your MainActivity.cs:using MyApp.WebServices;If you're unsure what the namespace is, locate the service reference folder in your project, open the auto-generated code file (like Reference.cs), and check the namespace declared at the top.
实例化并调用Web Service:
Now you can create an instance of the Web Service and call its methods within MainActivity (e.g., inOnCreateor a button click event). Here's an example using async/await to avoid blocking the UI thread:protected override async void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.activity_main); try { // Create Web Service instance var helloService = new HelloServiceClient(); // Call async method string response = await helloService.GetGreetingAsync("Xamarin Developer"); // Update UI with result Toast.MakeText(this, response, ToastLength.Long).Show(); } catch (Exception ex) { // Handle errors Toast.MakeText(this, $"Call failed: {ex.Message}", ToastLength.Long).Show(); } }Always prefer async calls in Android to prevent ANR (Application Not Responding) errors.
This issue almost always happens because your service reference namespace conflicts with the Web Service class name. For example, if you named the service reference namespace HelloService, and the auto-generated proxy class is also named HelloService, the compiler gets confused.
Fixes to try:
Use the full namespace + class name for instantiation:
If you don't want to re-add the service, explicitly specify the full path when creating the instance. Typically, the auto-generated client class appends "Client" to the service name, so it might look like this:var serviceInstance = new HelloService.HelloServiceClient();Here, the first
HelloServiceis the namespace, andHelloServiceClientis the actual client class.Re-add the service reference with a unique namespace:
Right-click the existing service reference → Delete, then re-add the service. This time, use a distinct namespace (e.g.,MyApp.Services.HelloService) that doesn't match the service class name. Afterward, import the new namespace and instantiate normally:using MyApp.Services.HelloService; // ... var helloService = new HelloServiceClient();
内容的提问来源于stack exchange,提问作者Khan Ataur Rahman

