Create ASP.Core WebAPI with Xamarin.Forms - c#

I want to launch a web api host when launching the application on xamarin, which I will make requests for, but I don’t understand how to connect the web api project and xamarin.forms or is there some other way of debugging the application.
I know that you can deploy the application on the azure service, but I want it to work locally

Those are two different applications.
Xamarin.Forms
Xamarin.Forms is an open-source UI framework. Xamarin.Forms allows developers to build Android, iOS, and Windows applications from a single shared codebase.
WebApi Core
ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the . NET Framework.
The first one is deployed on app stores and installed on devices.
The web api is deployed in web servers (like IIS) or on azure, and can be accessed over internet via http calls.
During development, you can build and deploy on your localhost. Check here for setup guidance: https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-3.1&tabs=visual-studio
You can consume your api from xamarin forms as described here:
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/data-cloud/web-services/rest
Example:
public async Task<List<TodoItem>> RefreshDataAsync ()
{
...
var uri = new Uri (string.Format (Constants.TodoItemsUrl, string.Empty));
...
var response = await _client.GetAsync (uri);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync ();
Items = JsonConvert.DeserializeObject <List<TodoItem>> (content);
}
...
}

This is pretty simple with Visual Studio 2019/2017.
After creating your Xamarin forms project, add an ASP.NET Core app to your solution; Visual Studio will manage everything. To debug the ASP project, set it as Startup project and click on the beautify Play/Start button and the browser should start and wait for a breakpoint or your stuff ...
You can debug Xamarin and the ASP Web app at the same time.
First we assume that the Web App act as an API endpoint for your app ; so that you will call it to send or request data ...
Then we assume you have a web client to call your endpoint and controllers in your Web app to receive that requests and respond ...
OK all that given, do this:
Right click on the solution in the Solution Explorer
Pick Properties
At the left side of the properties page, select Startup Projects
Multiple startup projects radio box
Action column set Start on every project you want to debug
Then ok and play
Hope this helped.
Useful links
Create an ASP App From the official documentation
Debug multiple projects answered by Max
.

You can run two instances of Visual Studio locally, one for the API project and the other for the Xamarin app.
In addition to Athanasios Kataras's answer, this documentation tells you how to connect to a local web service from the iOS Simulator or Android Emulator: https://learn.microsoft.com/en-us/xamarin/cross-platform/deploy-test/connect-to-local-web-services

Related

What's the difference between ASP.NET Core Hosted and Server-Side Blazor, really?

I'm still struggling to understand the difference between ASP.NET Core Hosted and Server-side Blazor. I know same question already exists, but it's not satisfying. In fact, I couldn't find the satisfying answer anywhere - the answers were more or less the same.
If hosted option uses server (IIS, Kestrel), then why server-side? Confusing... It's a shame that official documentation didn't shed the light either...
UPDATE
The confusion stems from the fact that we have THREE options to create Blazor application. After executing dotnew new --list I get:
dotnet new blazorserver (Blazor Server App)
dotnet blazorwasm (Blazor WebAssembly App)
However, there's a third option:
dotnet blazorwasm --hosted (or dotnet blazor --hosted)
It's the same as check box in Visual Studio when creating application:
The documentation says:
you have the option of configuring the app to use an ASP.NET Core
backend by selecting the ASP.NET Core hosted check box
But no explanation was provided what does it mean...
Re this part of your question:
However, there's a third option:
dotnet blazorwasm --hosted (or dotnet blazor --hosted)
It's the same as check box in Visual Studio when creating application:
The
documentation
says:
you have the option of configuring the app to use an ASP.NET Core
backend by selecting the ASP.NET Core hosted check box
But no explanation was provided what does it mean...
TL;DR
'Hosted' is used where you want the back-end of your site and the Blazor client using that back-end to both be hosted on the same website.
In Detail
I agree, the documentation really isn't terribly clear about all of this, but the explanation is actually simpler than it seems:
The Blazor app has to be 'hosted' somewhere
The first thing to remember is that the Blazor WebAssembly 'app' is not a standalone website, it's an app that's embedded in a website. In a lot of cases it will behave like a website, because it will be used as a Single Page Application, but that is by no means required.
Essentially the Blazor WebAssembly app is a series of files and a JavaScript file that are created by compiling/publishing your Blazor project.
Those files then need to be put on a website somewhere and the combination of the name of a div tag and the Blazor JS file produced for your site deals with wiring your app files into the WebAssembly part of the browser so that it's then rendered on the page.
The key here is that the website 'hosting' your Blazor app does not have to be an ASP.NET Core site. It could be any site, pure HTML, Drupal, whatever, it just needs to be shown on a browser that handles WebAssembly and JavaScript correctly.
However, if you're also writing the backend of your site in ASP.NET Core, you can reuse that site
So, your Blazor project doesn't have to be hosted in a website written in ASP.NET Core, but it does have to be hosted somewhere (so the user can see it).
If you're also writing the back-end of the site at the same time, e.g. if you're writing an API or SignalR hub to send and receive data from your Blazor client, and if you're writing that back-end in ASP.NET Core, then you can reuse that same site to also host your Blazor client.
This scenario is what the 'Hosted' option is for.
If you create a project using the template in the screenshot above, with the 'hosted' option ticked, you'll see that the [YourProjectName].Server project that's created is the Start Up project, but the index.html page that's shown when you run that project has come from the [YourProjectName].Client project.
This approach means you only have one site running on your server (which could be good or bad) and also means you won't run across any CORS issues.
But you don't have to have an ASP.NET Core site at all
If your Blazor site is a standalone site that doesn't read/write from any server, or if it only talks to 3rd party APIs or an existing Web API running on the older .NET Framework, then you don't actually need an ASP.NET Core site at all.
In that case you don't use the 'hosted' option.
Instead, you can simply publish your Blazor project and then take the files from the release folder and host them in any site.
Update
I see where you are coming from now. The confusion stems from the fact that you have an option called --hosted when using the client-hosted Blazor. This options means having Blazor to include ASP.NET Core runtime.
Why this option? Because you can write an offline app (e.g. calculator app) that does not need any kind of connection to external services, making ASP.NET Core irrelevant. However, you might want to write an online app that accesses online DB, external APIs, do verification, etc. For these kind of apps, you will need an ASP.NET Core stack to support your app.
Check this FAQ: https://github.com/aspnet/Blazor/wiki/FAQ#q-can-i-use-blazor-with-aspnet-core-on-the-server
Original answer
They are two hosting models: server-hosted, and client-hosted.
The difference is whether the app is hosted in server, or in client. Server hosting means your app logic runs in the server (you can think of it similar to what Web Forms is), you click on a button, an "Ajax" call sends the request, the server receives the request, and sends back the updated page. However, here it uses SignalR not Ajax, which is a low level socket communication (read efficient). And instead of updating a whole page, it updates only the relevant parts (thus it is a single page application).
On the other hand, client hosting means your logic runs within the browser. Think of it as if your C# logic is converted into JS, and it is embedded in the page. So the logic runs in the browser. This is possible after the introduction of WebAssembly which you might want to read about.
Let's say you want to create a calculator app. Your server hosted app will then need to communicate with the server to calculate and get the result for each calculation, while the client hosted does not need, and calculates the result in browser.
You might wonder, why we have two options. The reason being that support for WebAssembly (which a client hosted app relies on) is either incomplete or non-existant in many browsers, and performance differs widely too.
https://caniuse.com/#feat=wasm
The question is about the option "ASP.NET Core hosted" in Visual Studio, while creating a new Blazor Project with Blazor WebAssembly App.
Selecting this option scaffolds out 3 Projects for you (vs 1 WebAssembly project, if this option is not selected)
Server Side Blazor Project
Client Side Blazor Project (WebAssembly)
Shared project for shared entities between Server and Client Projects.
With this option you can have
Blazor WebAssembly only option for sections of your project where the logic can execute in browser.
Server hosted option where all the processing is done on server and only HTML is rendered onto the browser.
When deployed, all these projects go to the same location. So if you have a requirement for both Server Side as well as Client side options, then go for it.
I too had the same confusion while reading the documentation. But it was explained in Blazor webassembly section
dotnet blazorwasm - is a standalone project
dotnet blazorwasm --hosted (or dotnet blazor --hosted) - is a projected hosted with ASP.NET Core backing API's.
A hosted deployment serves the Blazor WebAssembly app to browsers from an ASP.NET Core app that runs on a web server.
The client Blazor WebAssembly app is published into the /bin/Release/{TARGET FRAMEWORK}/publish/wwwroot folder of the server app, along with any other static web assets of the server app. The two apps are deployed together. A web server that is capable of hosting an ASP.NET Core app is required. For a hosted deployment, Visual Studio includes the Blazor WebAssembly App project template (blazorwasm template when using the dotnet new command) with the Hosted option selected (-ho|--hosted when using the dotnet new command).
Here are my two cents.
Create a Blazor WebAssembly App with ASP.NET Core Hosted check box selected.
Once created observe the project references.
Note that the server project references client project.
I had this same confusion as others, that the client calls the server, and that they are two independent Visual Studio projects. So this project references puzzled me.
The fact is client project is hosted by and served by the server project. When we want to run the app, we need to run the server project and not the client project.
So when you want to run the Solution(App), you must ensure to set the Server project as the startup project and not both the server and client. Due to my initial misunderstanding, I was setting multiple startup project, thinking that the client(something like React App) calls the server(WebApi), and that they both should be running simultaneously, for the client to call the server.
The above is correct, but the following is INCORRECT.
If you do that, you get the following error, and this stung me.
Microsoft Visual Studio - One or more errors occurred. Failed to launch debug adapter error
And finally if you are thinking to dockarize by adding docker files and docker-compose files for different kinds of Blazor apps, do take a look at this github repo.
Specifically for this kind of apps that we are talking about take a look at this and this folder in that repo.
Blazor-WASM
The application can work offline after the first loading. As an Example If you make Loan calculator with Blazor WASM, you can send all the data, business logic and validation to the client side in the first load like loan types, loan rates, max repayment period like that then because of the logic also in client side, it don't need do the communication with the server again and again when you change the loan type or repayment period because business logic in client side using the user selected data Blazor can render the UI and show the result.
Blazor-server
Application use server to render the UI so as on the Loan application if user change the loan type blazor send that user change value to server using SignalR and in the server has data and the logic for get the result, after that server render UI and send UI changes to the client side using SignalR and redraw the UI in clients screen.
Blazor-ASP.NET Core Hosted
Visual studio generate 3 projects in the core hosted template
ClientProject - this is a Blazor-WASM application
ServerProject - this is a .NET CORE API
SharedClassProject - this is a class library that holds shared
objects between client and server
As the loan example in the first load loan types and calculation logic are loaded in client side.
If the user selects the loan type Blazor creates an http call to the API application to get the loan rates according to the selected loan type if the interest rate is in the db.
Then the user enters the repayment period because of calculation logic in the client side. Now the application can calculate the result and render the UI to show the result. So with this model you can keep some data or logic in the server and other data or logic on the client side.

How to run ASP.NET web api from github

I am new in asp.net and angular development.I dont know how to run asp.net web api from github. As we run angular code by using "ng build --prod --base-href https://ownername.github.io/repositoryname/ so i want to know could we run asp.net web api by using such kind of any command or something other which is used for this.
Basically i want to run my project on network i tried by IIS server but no result is showing so now i want to try github process
Help would be appricated
asp.net core apps have to run in a .net core process on a server so the hosting environment needs to specifically support this. a variety of web servers can be configured to proxy the requests. Unfortunately, I don't think GitHub allows running app processes for asp.net core.
However you ca easily deploy to azure with even a free account
https://learn.microsoft.com/en-us/aspnet/core/tutorials/publish-to-azure-webapp-using-vs?view=aspnetcore-2.2

Running a Angular front-end written in TypeScript in a C# Web API project?

Let's say I have an existing ASP.NET Web API project, complete with all the API controllers I need for some service. Previously when using this API, clients just did their typical URI routing to use this API.
Now, with ASP.NET Web API, they provide a simple front end. I'd like to add AngularJS to this, and I see one obvious way to do that, and that's through Angular's JavaScript library. How can one do this with TypeScript? I understand that TypeScript is a language that compiles down into JavaScript, which to me implies that I need to get some step in the build process for Visual Studio (not Visual Studio Code) that builds the TypeScript for my front end.
How can this be done? I have done some tutorials for TypeScript where they have you pull something off NPM that gives you the foundation for your website and you go from there. However, in all of these tutorials, I've done this in Visual Studio Code where you have the Angular CLI and you can ng serve --open to run the web server and develop your website, but I have no clue how to translate this feature into Visual Studio 2017 where both the Web API and the Angular front end are both running at the same time.
I envision the product I'm working on running on IIS and when clients navigate to the page, they'd be served up the Angular front end and the Web API would exist in the back end doing what it does, but I don't know how to marry these two together. Do you need to have two web servers running, one for the Web API and the other for the front end? If you can do it on a single web server, how can it be done? Thanks.
If you have a working API you can run this as normal, say on localhost:8000.
Now you create your SPA (angular or whatever) and run that on localhost:8001.
They run independently, all you do is query your endpoints, obviously passing paramters (say localhost:8000/api/something/3) in order to retrieve the data you're looking for.
If the API is not public, you simply don't expose it as such.

How to build an android app using MVC 5 and Web API?

I have an application developed in ASP.NET MVC 5 using EF6. My client needs some forms of that web app and reports on an android app. I just learnt that using ASP.NET 5, one can develop cross platform apps. How can I use my existing MVC 5 controllers,views and models with Web API to make an android app?
I have no experience with asp.net 5 and android development. I have studied a bit on internet that if I expose my data via RESTful API then I can make an Android app.
Regards.
Any web application or service can make functionality available via REST API. This basically means that you can control it and get data via GET, POST and other requests.
This means that it will be very difficult for you to expose anything but data, like controllers or views.
Since with the REST web service your app would need to be online anyway, you could just wrap your website inside an android app, similar to what BNK said or using other technologies, like a native view - should not make much of a difference.
Then basically, you have your web site (or a modified version thereof) hosted inside an android app.

How to serve static content from Azure Mobile Service C# backend

I'm running a mobile services instance (C# backend) and besides all the other functionality, I also need to host a few html pages and their respective css files.
Here is what I tried:
If I browse to http://<service-url>/myfile.html I get an 404 error. So I
created a myfile.html file and stuck it in the project root folder. Now, instead of 404, I get a blank page.
I tried going through the ContentController by putting the html file in <project root>\api\Content\Views\myfile.html. When I browse to http://<service-url>/api/Content/Views/myfile.html I get a blank page.
Update Dec, 2015
Now that Microsoft published App Services you should probably use that - create a mobile app and a web app and you're done.
Don't try to hack around with Mobile Services.
It always felt to me that Mobile Services were a half baked solution. It is more a competitor to Parse.com and similar BaaS and was missing a lot of the stuff you'd expect from an Azure service.
Update
The solution below does not work but it does teach you a lot about how the mobile service is built. The reason the solution does not work is that Azure refuses to upload the static files to the mobile service instance.
You start by understanding what is Owin and that mobile services are using one. This post helped me a lot.
Then you look in this link which explains how to build a file server using katana.
Here are short instructions:
Install nuget package Microsoft.Owin.StaticFiles.
Plug into the OwinAppBuilder and instruct it to use Katana's file server just before you run the original (put this in WebApiConfig.cs):
var originalAppBuilder = StartupOwinAppBuilder.OwinAppBuilder;
StartupOwinAppBuilder.Initialize(builder =>
{
builder.UseFileServer("/static");
originalAppBuilder(builder);
}
Create a static folder in your project root, put some files there and browse to <your service url>/static/somefile.html.

Categories