How to consume web API service from a webforms application? - c#

I have a webforms application in a big solution folder with multiple projects. I wanted to consume a web api application which is also a part of the solution. So my client looks like as follows.
function GetText()
{
$.getJSON("api/SiteUsers",
function (data) {
$("#TestText").append(data);
});
}
and the controller is a simple string returning action.
[HttpGet]
public string TestText()
{
return "this is a text";
}
when I try to call the service I get a 404 error the following link could not be found
http://localhost:1234/MyAspxProj/MyFolder/MyPage/api/SiteUsers
I can understand it is probably because it is trying to find the resource from within the webforms application. How can I call the web api service? I am open to all suggestions and advice.

lets say your API is hosted on localhost:1111 and your webforms application is hosted on localhost:2222
first make sure you can get the results of the API you just created by going to:
localhost:1111/api/SiteUsers
once you are sure that the above URL is returning what you expect, you can be sure that your API is set-up correctly.
Now lets come to the next issue, accessing API from another application (i.e. not having the same Host as the API i.e. localhost2222)
To access APIs from an application that is on another domain, you need to enable CORS support on the WebAPI. There are manay resources on the internet that will explain you how you can achieve this: google for enabling cors in web api 2
Once you have set-up CORS on your web api project, you will be able to access your API from any application.
Remember: you only need to enable CORS if the client is on different domain AND the client is a web based client (which in your case it is i.e. web forms application)
I hope this will give you some direction.

Based on the info you've provided, it looks to me like you're not putting in the correct url. Assuming your [HttpGet] function is within a file at "api/SiteUsers", you would use a url like this: "api/SiteUsers/TestText"

Related

How to set Custom Base URL in Azure App Service with .Net Core?

I have created a web application in .Net core(v5.0) and hosted it in Azure App Service. I have created a view and that allows me to add a new URL based on that create a new subdomain in the same service and publish code in that. This concept also uses in Jira software where our <projectname>.atlassian.com
Eg:
I have added dev in a text box then-new subdomain added like. dev.<myappservicename>.azurewebsites.net
In this case, all code copy and run this code properly.
Main Domain:
Base URL(Created URL): <myappservicename>.azurewebsites.net
Custom URL(Added from View): dev.<myappservicename>.azurewebsites.net
,
admin.<myappservicename>.azurewebsites.net
Technology Specification:
.Net Core(5.0)
C#
Azure App Service
If anyone has an idea then suggest thought.
It helps me a lot.
You can use restapi or .net sdk to create subdomain.
From your description, I see that there should be no need to redeploy your webapp, so if there is a business need, it is recommended to identify it through the program, what is the input url of the browser, to process your program.
Eg:
company1.<projec_tname>.azurewebsites.net
Get HttpRequest url to handle company1's bussiness.
company2.<projec_tname>.azurewebsites.net
Get HttpRequest url to handle company2's bussiness.

Blazor httpclient endpoint address configs

I'm playing around with Blazor in .net core 3 preview 5.
My solution is quite simple, with one project for the web api and a second for the blazor client app.
The api is currently serving on localhost:5000 and the blazor app on localhost:5001, and I'm using httpclient to make http calls to the rest endpoint.
One thing in struggling with is understanding the best way to avoid baking in the api server URLs into the blazor app.
Is there am established pattern which will enable be to specify the base url by config or run time?
Edit to add info from comment:
Ultimately, I'd like to run it in a container in our test k8s cluster, that means the target url for the api would change to (say) api.test.companydns.com. the blazor app will end up running inside a container, so ideally I could pass in the api url as a parameter. I wasnt sure of the best way to do that as the blazor code ends up being executed on the client side
Question:
Is there am established pattern which will enable be to specify the base url by config or run time?
Answer: Yes, the base Uri of your Blazor client side is determined by the <base> HTML element set in /wwwroot/index.html like so:
<base href="/" />
Hope this helps...
I've done a bit of a hack which works for me (posted more to show I'm putting effort into solving the problem for myself!!):
I've added a config file to wwwroot\config\config.json which contains:
{
"apiBaseUrl": "api.url.com"
}
Next, I've created an AppState.cs which used the HttpClient to download and store the base URL (Defaul DI instance of HttpClient has a BaseURL of the url serving the Blazor client app).
The AppState class is then made available using DI, so now all my Services can make calls to the new endpoint.
Lastly, I can use a build pipeline / CI / Docker volume / K8s config map to supply the relivent config.json depending on the hosting environment and without further changes to any Blazor app code.

How to implement a callback URL to receive a json data in c#

For some days now i have been struggling on a project where i need to provide a URL to enable me to receive a JSON response(precisely this my first time of calling a web API)
This is the scenario:
- First the company has a web service that i need to consume and send a bill prompt to our client and so far it has been successful
- Second , they ask me to implement a callback and give them the URL where they will call me to send the status of the bill whether our client has confirm the bill prompt or not(this is where i am stacked)
When i get the JSON data i can easily use it to do what i want but my problem is how to implement the web page that the company will call to send the status.
Please a sample code will help me a lot.Thanks
What you are trying to achieve is called WebAPI. You expose HTTP endpoints using Controllers to the Internet and consumers of your API may utilize them to POST the status back.
You are describing creating an API. Basically, you create an endpoint url using a controller in C#. It's within this controller that you receive data from "the company" and process it, and do whatever you need to do after that. If you use the standard MVC framework build into C#, it's fairly straight-forward. Here is an example of a callback url we are using in a three-legged OAuth procedure. The last step involves a third party sending a request to our callback url and posting some data. We are using a model as a parameter. But you can use simple structures (int, string, etc) as well. As log as the names of your params match the names that the third party sends in their query string or POST, the MVC framework will handle the variable assignment automatically. The serialization/deserialization is built in to the framework.
Here is a small example of how we have implemented a callback url in one of our apps:
public class MyAuthenticatedController : Controller
{
public ActionResult Index([FromUri]MyAuthenticatedModel model)
{
logTheResponse(model);
if (model == null)
{
throw new HttpException(401, "Auth Failed");
}
}
}
The third party would hit the url:
http://app.mydomain.com/myauthenticated
Using the GET method.
If you don't want to build an ASP.NET Web API Project, you can do this easily with an Azure Function.
See: https://learn.microsoft.com/en-us/azure/azure-functions/functions-create-generic-webhook-triggered-function

How can a WCF Service obtain Query Parameters?

I'm working on an Azure service for a Windows Phone app. I need the Azure Service to access the users' OneDrive. Following this article, my scenario should be:
The user sign in to Windows Live on the WP app.
The Live web service sends the authorization code to a redirect URI that I defined, with the code appended as a query parameter named code, as:
http://www.example.com/callback.php?code=2bd12503-7e88-bfe7-c5c7-82274a740ff
I get the authorization code and access the users' data
After investigating a lot in Service, I still can't find a way to capture the query parameter in my web service. As I am new to this area, I don't know where to focus on. I'll be really appreciated if you can give my an advise or answer my following questions:
Can I access the service just using the url with parameter in a browser? How can I see if the service is working properly?
An article mentioned using WCF [Web Get] attribute to get Query Parameters, but I still don't know how to implement both the IService1.cs and Service1.cs file, could you give me a sample about how to access the value of Query Parameter?
Thanks!
I'm not sure if i understand your problem properly but if you want your RESTfull WCF service to be the callback receiver for the request code, your Service must be hosted with a WebHttpBinding and a ServiceContract similar to this one.
[ServiceContract]
public interface IService
{
[WebGet(UriTemplate = "callback?code={requestCode}")]
void OAuthCallback(string requestCode);
}
So if the base address of your Service is "http://service.mydomain.com/MyService.svc" the OAuthCallback Method will be called when a http GET request to "http://service.mydomain.com/MyService.svc/callback?code=RequestCode" is made.

C# Web API - Security for some of the GET requests

On an existing host I've added Web API Models & Controllers. I've added the following four:
Products
Orders
Categories
Users
When someone accesses the localhost:port\api\products, it returns all the products in JSON format.
The Create, Update and Delete statements are completely disabled, so we are only able to use GET-requests on the API (so either \api\products for a list of all products or api\products\# for a single products with id #).
Because the other CRUD's aren't used, there isn't a lot of security that should be added to the Web API, except for one thing: The Users
These will also return emails and such, which would be better to keep private and unreadable without the proper authorization (without entire log-in pages, but a way to authenticate yourself when accessing the Web API in for example Android HttpGetRequests).
So, the question: How should I add authorization for only the UsersController accessed by the Web API.
And, how can I encrypt the JSON in C# and decrypt it in Android again. If this second part is too big to answer I'll make a new question later on, my main focus is the low-end [<- without log-in pages, so built in into the GET-request] authorization of the Web API's GET-request for Users.
Edit 1: I did found this link where a new project is made with Authorization Changed to Individual Users. I also see that the user is registered and then logged in with POST and GET requests.
The following questions came into mind when reading through this link:
How to change the Web API's Authorization to Individual Users on an existing project?
Our authorization is done through OAuth (mainly Google-account) with our work e-mail address. I guess it's not possible / easy to authorize in the same way as in the link with a Google-account on Web API GET-requests.
Edit 2: After using the first link provided by Vladimir Gondarev I've added the [Authorize] to both the Get methods in the UsersController. In my project everything else was already used before, like a class that uses the AuthorizeAttribute, so just adding the [Authorize] was already enough for the first step. Now in the browser I get an unauthorized (JSON) back when I'm not logged in, which is good.
The next step would be to add the OAuth-authorization to the Android app, but that is an entire new problem / question that I will look into first before asking a new stackoverflow-question.
The simplest solution would be "Basic Authentification". In order to to implement it you have to derive from AuthorizeAttribute and then apply it to a method or a controller.
Here you find further info:
What is basic Authentification:
http://www.asp.net/web-api/overview/security/basic-authentication
Implementation:
ASP.net Web API RESTful web service + Basic authentication
You don't have to encrypt anything as long as you use HTTPS transport.

Categories

Resources