I\'m trying to connect to an on-prem MS SQL database from a universal windows app. I\'m making a LOB app using UWP, to support desktop, tablet and mobile use. When trying to
Note: From windows 10 Fall Creators Update (16299) we can directly access SQL Server database using .NetStanded 2.0
As there is no direct way to connect to SQL Server, we need to create an API for our database in order to connect to SQL Server.
This solution describes
Launch Visual Studio Installer and click Modify
Install ASP.NET and web development
Add new project in your solution
Select ASP.NET Web Application (.Net Framework) and give a project name
Select Web API and click OK
Add new item in Models folder
Select ADO.NET Entity Data Model and give it a name
Select EF Designer from database and click Next
Click New Connection
Configure your connection, click OK and click Next
Select Entity Framework version and click next
Select Databases and Tables to be connected and Click Finish
Rebuild your project before doing forther
Add new Controller in Controllers folder
Select Web API 2 Controller with actions, using Entity Framework and click Add
Select Model class (table name) and Data context class (database name) from the drop-down list box and click Add
Set this project as the startup project
Run the project in a web browser
Now your browser will open a localhost site. Click API in top
This page shows all the API available from your project
Copy any API link from below and replace it with the "Help" in URI and press Enter. Now you should able to see your data from the SQL Server database
HttpClient httpClient = new HttpClient();
var jsonReponse = await httpClient.GetStringAsync("http://localhost:xxxxx/api/LogIns");
logInResult = JsonConvert.DeserializeObject>(jsonReponse);
You can get the model class from Models
Just create the same class in your UWP project
var logIn = new Models.LogIn()
{
Username = "username",
Password = "password"
};
var logInJson = JsonConvert.SerializeObject(logIn);
HttpClient httpClient = new HttpClient();
var httpContent = new StringContent(logInJson);
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
await httpClient.PostAsync("http://localhost:56267/api/LogIns", httpContent);
For more info about JSON Serialization And Deserialization Using JSON.NET Library In C#