how to call webapi function from codebehind in webforms - asp.net

I added a web api in my asp.net web forms project. I want to call this web api directly from my code behind. Both my code behind and web api are in the same project. Both are in same namespaces.
Is it the right way to instantiate the controller class and directly call the method in it(in webforms project - in button click). like:
SampleController obj = new SampleController();
Dictionary<String,String> values = obj.MyMethod();
Please suggest an alternative way, if this method is incorrect.
(This web-api is also consumed by another windows service using httpclient)
Thanks in advance.

Related

Using WCF http web service in ASP.NET application

We have web application written in ASP.NET webforms with some asmx web services. Now we want to add some toher web services, which will serve different purpose than the old ones. We decided to use WCF framework.
My colleague created a new project in our solution, where he implemented the web service. Unfortunatelly he did not use the WCF* project templates, but normal console application with the following method for starting the WS:
public static void StartWS() {
if (_selfHost!=null)
StopWS();
Uri baseAdress = new Uri(WSIntegrationService.ServerUrl);
_selfHost = new ServiceHost(typeof(WSIntegrationService), baseAdress);
_selfHost.AddServiceEndpoint(typeof(IWSIntegrationService), new WSHttpBinding(SecurityMode.None), WSIntegrationService.EndPointName);
_selfHost.Description.Behaviors.Add(new ServiceMetadataBehavior { HttpGetEnabled = true });
_selfHost.Open();
logger.Info("Integration WS started on adress " + baseAdress);
}
Now I have to integrate the project to our web application (another project in solution).
What is the easiest way to do it?
How can I ensure that both - the old asmx service as well as the new WCF service is operational?
In the end the solution was not that hard:
In web app project choose Add New Item -> WCF Service. This should create Service.svc, Service.svc.cs and IService.cs. It also modifies your web config. Now you can try if it works, with the auto generated method DoWork. Simply use something like SoapUI app to do that. ALso you can try to browse to the svc file and check the wsdl (e.g.http://localhost:2753/WSIntegration/Service1.svc?wsdl)
Delete the files IService.cs and Service.csv.cs. Modify the Service.svc file, so it contains just the reference to the class implementing the WS, e.g. like this:
That's all. I haven't deploy the solution to the IIS yet, but I don't expect any problems there. As soon as I will do that. I will update the unswer if any additional steps will be needed.

What is the advantage of using web API over web method in ASP.NET

I am familiar with web method. Now I got a suggestion to use web API instead of web method. I had done a demo of ASP.NET web API it's more closer to a MVC architecture am using the classical asp.net web development. I don't like to mess up the controller (MVC concept) with classical development.
My web Method :
[WebMethod]
public static string GetName(int id)
{
return "testName";
}
My Web API controller:
public class MyController : ApiController
{
[HttpGet]
public string GetName(int id)
{
return "testName";
}
}
am really confused on this issue any one have a better idea on the same.
What is your suggestion on the same which is the better option?
How can i compare, if both having same piece of code?
The classic ASP.NET WebServices (what you call WebMethod) are a deprecated technology. There is no longer any active development. The ASP.NET Web API is a complete rewrite of the web stack from Microsoft in which you have far greater control for creating RESTful web services. This doesn't mean that you should choose between one or the other. There's also ServiceStack. If you are starting a new project you should stay away from classic webservices. If they are still present in the .NET framework it is for compatibility reasons with legacy code.
Complementing Darin's answer, if you want to test your method from ApiController, you can inject the object's dependencies using an DI container (http://www.asp.net/web-api/overview/extensibility/using-the-web-api-dependency-resolver). The dependency injection is done automatically.
However, with webmethods, you can't use DI in that way because webmethods must be static. If you insist in using DI, you need to instantiate and call the container directly in each of the webmethods to get the dependencies to work on.

Using MVC routing engine from a self hosted dll (outside asp.net)?

I'm using WCF Web API to create a self-hosted/InProcess REST Service (HttpServiceHost) that the client app will use. All the examples for the web api use ASP.Net routing engine. Would it be possible to use the routing engine outside of Asp.net?
To give you an idea what i'm doing, here is the contructor of my Service Class that the client will new up:
Public Sub New()
ObjectFactory.Initialize(Sub(x)
x.For(Of IIssueTrackerRepository)().Use(Of IssueTrackerRepository)().Ctor(Of String).Is(ConfigurationManager.ConnectionStrings("Dev").ConnectionString)
'x.ForConcreteType(Of IssueTrackerResource)().Configure.Ctor(Of String).Is(ConfigurationManager.ConnectionStrings("Dev").ConnectionString)
End Sub
)
_host = New HttpServiceHost(ObjectFactory.GetInstance(Of IssueTrackerResource), "http://localhost:8000")
_host.Open()
End Sub
If you can link any examples, it would be extremely helpful.
As far as I know: not yet.
But as Web API is still under development it may be part of a future Preview.

Winforms server side consumed by ASP.NET, WCF?

Where can I find a tutorial/sample of asp.net page consuming a WCF service that uses a winforms application server side?
Thanks
You are mentioning two separate and independent operations:
Consuming a WCF service from an ASP .Net application
Creating a WCF service that uses a win forms application
Which of them is the actual problem? Exposing functionality as a service separates the service consumer from the service provider. The service consumer (the ASP .Net application in your case) will never need to know the service provider (the WCF application) is implementing its functionality behind the scenes. All it needs to know is the public interface exposed by the service.
Update
If you are new to WCF, the video tutorials available here might be a good starting point. They present you the basic knowledge of exposing as well as consuming a service with WCF.
Now, related to "that uses a winforms application server side". I assume that what you are trying to do is expose in the service some of the functionality available in the win forms application. If that is the case all you have to do is reference the exe of the forms app (with Add reference in Visual Studio) inside the WCF app and call all the needed methods from there.
Even cleaner from an architectural perspective would be to separate the user interface (UI) and business logic (BL) of your win forms application in separate projects, which will result in separate binary files after compilation (an exe file corresponding to the UI and a dll for the BL). Then you will only need to reference the BL corresponding dll in the WCF service.
OK, This is what you need to do:
Create a Solution with a ASP.Net project in it. (Project A)
Go to File > Add > New Project and add a Windows Forms application. (Project B)
So, now you have two projects in your solution,
Add a reference from project B to project A.
Add a method that returns the main form of project B in Program.cs, here is an example:
public static class Program
{
public static MainForm mainForm;
[STAThread]
public static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
mainForm = new MainForm();
Application.Run(mainForm);
}
public static MainForm RunForm()
{
Main();
return mainForm;
}
}
Define a new Thread in Global.asax > Application_Start to call the RunForm method and store the result in a static variable. example:
public static MainForm mainForm;
public void Application_Start()
{
new Thread(
() => { mainForm = Program.RunForm(); }
).Start();
}
(Don't forget to use using B;)
(If you don't run the form application in another thread, your website doesn't load.)
So, now you can access the main form using Global.mainForm
You can define some methods for showing MessageBox in MainForm class, and call them from the website! (The form doesn't need to be shown at all)

call web methods directly from other project

I am working with .NET solution project and there are a couple projects in side of the solution. One of projects has asmx file. Now, my question is that is it possible to call web methods in the asmx file directly from other projects in same solution instead of adding web reference of it?
Thanks.
ASMX files are usually placed in ASP.NET projects which are not suitable to be referenced by other projects. For this reason I would recommend you refactoring the functionality into a class library that will be referenced from the web service and from other projects where you directly call the methods:
var result = new SomeClass().SomeMethod();
and in the web service:
[WebMethod]
public string SomeMethod()
{
return new SomeClass().SomeMethod();
}

Resources