简体   繁体   中英

How do i send a string content to Dot Net Web API(Server) from Xamarin Android App(Client)?

In Xamarin

var request = new HttpRequestMessage();
                request.RequestUri = new Uri("http://localhost:53325/Values/UploadFile?file=");
                request.Method = HttpMethod.Get;
                request.Headers.Add("Accept","application/json");
                //HttpResponseMessage reponse = await client.PostAsync(UploadServiceBaseAddress, stringContent);
                HttpResponseMessage responseMessage = await client.SendAsync(request);
            Toast.MakeText(this, Convert.ToString(responseMessage), ToastLength.Long).Show();
            if (responseMessage.IsSuccessStatusCode)
            {
                var responseData = responseMessage.Content.ReadAsStringAsync().Result;
            }

            HttpContent content = responseMessage.Content;
            var jsonn = await content.ReadAsStringAsync();

In Dot Net Web API

    public class ValuesController : Controller
    {

        [System.Web.Http.HttpGet]
        [System.Web.Http.Route("api/Values/")]
        public ActionResult UploadFile(string file)
        {
            return Json(new { status = "success"},JsonRequestBehavior.AllowGet); //JsonRequestBehavior.AllowGet
        }
}

How do i send a string contents from Xamarin to Dot Net Web API and return the SUCCESS message back to Xamarin

In your Web API Project, you have to make sure that it is running on the IP Address of the machine as provided by the router of your network and not on your loopback (" http://localhost:53325 ").

You can do this by changing your Program.cs in your Web API Project. Here's the code for it:

using System.IO;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;

namespace MyApi
{
        public class Program
    {
        public static void Main(string[] args)
        {
            //UseUrls does the trick.
            var host = new WebHostBuilder()
                .UseUrls("http://*:53325")
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>()
                .Build();

            host.Run();
        }
    }
}

Once your code is running on the network, you can start testing on a real Android Device. Here's the sample Web API Action ("Get method")

using Microsoft.AspNetCore.Mvc;

namespace MyApi.Controllers
{
        [Route("api/[controller]")]
        public class ValuesController : Controller
        {
                [HttpGet]
                public ActionResult UploadFile([FromQuery]string file)
                {
                        return new ObjectResult(new { status = "success = " + file });
                }
                [HttpGet]
                [Route("test")]
                public string Test() { return "test"; }
        }
}

To make sure the app will run fine, run the Web API Project, and connect Android Device to same LAN / WiFi, now goto the /api/values/test action, and you should see the "test" string. If that's working, you can proceed with the Xamarin.Android Project.

As Data Retrieval is achieved with the HttpClient class, it can be written in a portal .NET Standard Project. I wrote this sample class:

using System.Net.Http;
using System.Threading.Tasks;

namespace ClientApp.Portable
{
    public class SendReceiveTest
    {
        public static async Task<string> Test(string data)
        {
            using (var client = new HttpClient())
            {
                var uri = $"http://192.168.0.103:53325/api/values?file={data}";
                var response = await client.GetAsync(uri);
                var stringData = await response.Content.ReadAsStringAsync();
                return stringData;
            }
        }
    }
}

Now, in your activity, you can add the data retrieval to any event, as follows:

using Android.OS;
using ClientApp.Portable;

namespace ClientApp
{
    [Activity(Label = "ClientApp", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            var textView = FindViewById<TextView>(Resource.Id.message);
            var getDataButton = FindViewById<Button>(Resource.Id.getData);

            getDataButton.Click += async (sender, args) =>
            {
                var data = await SendReceiveTest.Test("test.txt");
                textView.Text = data;
            };
        }
    }
}

The TextView's Text will be replaced with the returned data. You can do anything with the data; set as Toast Message, parse JSON to object using Libraries like JSON.NET, etc,.

End Result: 在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM