Call web service method from generic handler - asp.net

In my asp.net application I have web service ~/service.asmx and generic handler ~/handler.ashx. How can I call web service's method from the generic handler? For example, in web service I have string SayHello(string name) method. To call it I need to make a request to /service.asmx/SayHello. What I need is to call that when user requests the generic handler /handler.ashx.

Add service reference (which will create a proxy class) and create an instance of Webservice proxy class and call this method. If web-service is located in your current web-app then you may instantiate that class and call method as we call the regular method.

Related

What is the complete lifecycle of an OData controller http request in WebApi 2

I wonder what is the full lifecycle of an odata http request over an ODataController hosted in IIS.
For instance:
What are the IIS pipelining steps ?
How is the request handled when entering the ASP.NET controllers area ?
When routing is applied ?
When the Attributes such HttpPost, ApplyFilter are applied ?
Maybe this thread can help you:
The ASP.NET Web API 2 HTTP Message Lifecycle in 43 Easy Steps
It all starts with IIS:
IIS (or OWIN self-hosting) receives a request.
The request is then passed to an instance of HttpServer.
HttpServer is responsible for dispatching HttpRequestMessage objects.
HttpRequestMessage provides strongly-typed access to the request.
If one or more global instances of DelegatingHandler exist on the pipeline, the request is passed to it. The request arrives at the instances of DelegatingHandler in the order said instances were added to the pipeline.
DelegatingHandler instances can skip the remainder of the pipeline and create their own response. I do exactly this in my Custom Validation with FluentValidation post.
If the HttpRequestMessage passes the DelegatingHandler instances (or no such handler exists), then the request proceeds to the HttpRoutingDispatcher instance.
HttpRoutingDispatcher chooses which routing handler to call based on the matching route. If no such route exists (e.g. Route.Handler is null, as seen in the diagram) then the request proceeds directly to Step 10.
If a Route Handler exists for the given route, the HttpRequestMessage is sent to that handler.
It is possible to have instances of DelegatingHandler attached to individual routes. If such handlers exist, the request goes to them (in the order they were added to the pipeline).
An instance of HttpMessageHandler then handles the request. If you provide a custom HttpMessageHandler, said handler can optionally return the request to the "main" path or to a custom end point.
The request is received by an instance of HttpControllerDispatcher, which will route the request to the appropriate route as determined by the request's URL.
The HttpControllerDispatcher selects the appropriate controller to route the request to.
An instance of IHttpControllerSelector selects the appropriate HttpControllerDescriptor for the given HttpMessage.
The IHttpControllerSelector calls an instance of IHttpControllerTypeResolver, which will finally call...
an instance of IAssembliesResolver, which ultimately selects the appropriate controller and returns it to the HttpControllerDispatcher from Step 11.
NOTE: If you implement Dependency Injection, the IAssembliesResolver will be replaced by whatever container you register.
Once the HttpControllerDispatcher has a reference to the appropriate controller, it calls the Create() method on an IHttpControllerActivator...
which creates the actual controller and returns it to the Dispatcher. The dispatcher then sends the request into the Select Controller Action routine, as shown below.
We now have an instance of ApiController which represents the actual controller class the request is routed to. Said instance calls the SelectAction() method on IHttpActionSelector...
Which returns an instance of HttpActionDescriptor representing the action that needs to be called.
Once the pipeline has determined which action to route the request to, it executes any Authentication Filters which are inserted into the pipeline (either globally or local to the invoked action).
These filters allow you to authenticate requests to either individual actions, entire controllers, or globally throughout the application. Any filters which exist are executed in the order they are added to the pipeline (global filters first, then controller-level filters, then action-level filters).
The request then proceeds to the [Authorization Filters] layer, where any Authorization Filters which exist are applied to the request.
Authorization Filters can optionally create their own response and send that back, rather than allowing the request to proceed through the pipeline. These filters are applied in the same manner as Authentication Filters (globally, controller-level, action-level). Note that Authorization Filters can only be used on the Request, not the Response, as it is assumed that if a Response exists, the user had the authorization to generate it.
The request now enters the Model Binding process, which is shown in the next part of the main poster. Each parameter needed by the action can be bound to its value by one of three separate paths. Which path the binding system uses depends on where the value needed exists within the request.
If data needed for an action parameter value exists in the entity body, Web API reads the body of the request; an instance of FormatterParameterBinding will invoke the appropriate formatter classes...
which bind the values to a media type (using MediaTypeFormatter)...
which results in a new complex type.
If data needed for a parameter value exists in the URL or query string, said URL is passed into an instance of IModelBinder, which uses an IValueProvider to map values to a model (see Phil Haack's post about this topic for more info)....
which results in a simple type.
If a custom HttpParameterBinding exists, the system uses that custom binding to build the value...
which results in any kind (simple or complex) of object being mappable (see Mike Stall's wonderful series on this topic).
Now that the request is bound to a model, it is passed through any Action Filters which may exist in the pipeline (either globally or just for the action being invoked).
Once the action filters are passed, the action itself is invoked, and the system waits for a response from it.
If the action produces an exception AND an exception filter exists, the exception filter receives and processes the exception.
If no exception occurred, the action produces an instance of HttpResponseMessage by running the Result Conversion subroutine, shown in the next screenshot.
If the return type is already an HttpResponseMessage, we don't need to do any conversion, so pass the return on through.
If the return type is void, .NET will return an HttpResponseMessage with the status 204 No Content.
If the return type is an IHttpActionResult, call the method ExecuteAsync to create an HttpResponseMessage.
In any Web API method in which you use return Ok(); or return BadRequest(); or something similar, that return statement follows this process, rather than any of the other processes, since the return type of those actions is IHttpActionResult.
For all other types, .NET will create an HttpResponseMessage and place the serialized value of the return in the body of that message.
Once the HttpResponseMessage has been created, return it to the main pipeline.
Pass the newly-created HttpResponseMessage through any AuthenticationFilters which may exist.
The HttpResponseMessage flows through the HttpControllerDispatcher, which at this point probably won't do anything with it.
The Response also flows through the HttpRoutingDispatcher, which again won't do anything with it.
The Response now proceeds through any DelegatingHandlers that are set up to handle it. At this point, the DelegatingHandler objects can really only change the response being sent (e.g. intercept certain responses and change to the appropriate HTTP status).
The final HttpResponseMessage is given to the HttpServer instance.
which returns an Http response to the invoking client
Looking at the source code ,ODataController is another controller which is inherited from
ApiController with custom routing and formatting. So I guess all the logic applied for ApiController
applies to that as well.It also has Custom Formatting and Custom Routing applies using ODataFormatting and ODataRouting
What are the IIS pipelining steps ?
IIS pipelining steps are same like any other mvc controller .In essense,we have all the httpmodules and handlers which forms the pipeline.More details can be found asp.net application lifecycle. From this pieline,when an mvc request comes URLRoutingModule,MvcRouteHandler and Mvchandler works in tandem to serve an MVC request. Explained detailed for the next question.
How is the request handled when entering the ASP.NET controllers area ? When is routing applied ?
Everything starts with an ODataController .Almost everything in MVC is extensible(13 extensibility points in asp.net mvc) you name it and all those points are extended for OData. e.g Starting with Custom Controllers,we have
custom ODataActionSelector which is from IHttpActionSelector .You can find a sample implementation here
IActionValueBinder ,sample implementation here
IContentNegotiator
etc like this many more.
/// Defines a base class for OData controllers that support writing and reading data using the OData formats
/// </summary>
[ODataFormatting]
[ODataRouting]
[ApiExplorerSettings(IgnoreApi = true)]
public abstract class ODataController : ApiController
Receive first request for the application -> In the Global.asax file, Route objects are added to the RouteTable object.
Perform routing -> The UrlRoutingModule module uses the first matching Route object in the RouteTable collection .From ODataRouting, The routes are added to RouteTable collection.
Create MVC request handler -> The MvcRouteHandler object creates an instance of the MvcHandler class and passes the RequestContext instance to the handler
Create controller -> The MvcHandler object uses the RequestContext instance to identify the IControllerFactory object to create the controller instance with
Execute controller -> The MvcHandler instance calls the controller's Execute method
Invoke action -> For controllers that inherit from the ControllerBase class, the ControllerActionInvoker object that is associated with the controller determines which action method of the controller class to call, and then calls that method
7.Action returns all custom CreatedODataResult,UpdatedODataResult etc
There are Custom ODataMediaTypeFormatter registered for ODATA to format the data.

what is the difference between Asp.net page life cycle and Asp.net Mvc page life cycle?

what is the difference between Asp.net page life cycle
and Asp.net Mvc page life cycle ?
Asp.net page life cycle Simply remember SILVER U
s- Start
I-Initialization
L-Load
V- Validate
E- Event handling
R -Rendering
U -Unload
What actual difference in Mvc and Asp.net page ?
ASP.NET Page Life Cycle is totally different from webforms, there are no events like we have in web forms for example: pre render, oninit etc. whenever we request a URL the only thing happens is, an instance of a controller is crated and some action method is called of it which results in rendering the View as HTML as response in the browser.
ASP.NET MVC Page Life Cycle:
According to MSDN the following are the main steps involved in asp.net mvc page life cycle:
1) Routing
routes url to its controller and action
In ASP.NET application each asp.net page implements the IHTTPHandler interface.
This interface has a ProcessRequest() method that gets called when you request the page. The ProcessRequest() method is responsible for processing the request and generating the response. So in ASP.NET application it is simple, you request for a page in the url like http://mysite1\default.aspx and then it search for that page on the disk and execute the processrequest method and generate the response.
However in MVC application it doesn’t work in that way. There is no physical page exist for a particular request. All the requests are routed to a special class called Controller. The controller is responsible for generating the response and sending the content back to the browser.
2)Url Routing Module intercepts the Request:
Whenever you make a request against an ASP.NET MVC application, the request is intercepted by the UrlRoutingModule HTTP Module.
When the UrlRoutingModule intercepts a request, the first thing the module does is to wrap up the current HttpContext in an HttpContextWrapper object.
The HttpContextWrapper object derives from HTTPContextBase class.
3)MVC Handler Executes
MVCHandler also inherit from the IHTTPAsyncHandler. When MVC Handler executes it will call the BeginProcessRequest method of the httpAsyncHandler asynchronously.
When the process request method is called a new controller gets created. The controller is created from a ControllerFactory. There is a ControllerBuilder Class which will set the ControllerFactory.
You can create your own ControllerFactory as well but by default it will be DefaultControllerFactory. The RequestContext and the name of the Contoller will be passed to the method CreateController Method to get the particular Contoller.
4) Controller Executes
controller is called and its action called requested by user.
The Execute() method starts by creating the TempData object. TempData is a dictionary derived from TempDataDictionary class and stored in short lives session and it is a string key and object value.
The Execute() method gets the Action from the RouteData based on the URL.The Controller Class then call the ContollerActionInvoker that builds a list of parameters from the request.
These parameters, extracted from the request parameters, will act as method parameters.The parameters will be passed to whatever controller method gets executed.
Finally It will call the InvokeAction method to execute the Action.
5)Render View Method Called
at last when we call reutrn View() Render View method is called and puts reponse on the page to be displayed.
The Controller typically either executes either the RedirectToAction Method or the RenderView Method. When you call a controller’s RenderView() method,the call is delegated to the current ViewEngine’s RenderView() method.
The WebFormViewEngine.RenderView() method uses a class named the ViewLocator class to find the view. Next, it uses a BuildManager to create an instance of a ViewPage class from its path.
Next, if the page has a master page, the location of the master page is set If the page has ViewData, the ViewData is set. Finally, the RenderView() method is called on the ViewPage.
Abstract Explanation Diagram:
In Depth Diagram:
Request Flow"
Here is the asp.net mvc request flow:
Reference Links
For Understanding in details refer to Understanding of MVC Page Life Cycle
Also Here is another good article explaining MVC Page Life Cycle
ASP.NET Web Forms
ASP.NET Web Forms use Page controller pattern approach for rendering
layout. In this approach, every page has its own controller, i.e.,
code-behind file that processes the request.
In order to achieve stateful behavior, viewstate is used. Purpose was
to give developers the same experience of a typical WinForms
application.
ASP.NET MVC
It uses Front Controller approach. That approach means a common
controller for all pages processes the requests.
ASP.NET MVC approach is stateless as that of the web. So there is no
concept of viewstate.
But in actual in MVC there is no page life cycle per se (because there is no 'page' object), but there is a request processing pipeline:
You could take help from here nice description or refer to MVC4 and page life cycle?

Server side callback function ajax web service asp.net

I'm using Web Service to handle ajax request in my project. I need to call a server side function to count users online when a new request is proceed.
If you want to call Server side method into Client side then,you have to transform this method as a PageMethod and then call this method i.e GetOnlineUser() from client side code; i.e. using JavaScript.
To enable the method as a PageMethod, add the attribute [WebMethod] on top of the GetOnlineUser method in .aspx code behind file.
if you are using asp.Net membership provider then simply call Membership.GetNumberOfUsersOnline().
And if you are not using membership you have to implement your own custom counter...

Can we expose public properties of a webservice on the client side?

I understand that webservices are stateless. I want to know if there is any way we can expose the public properties (getters and setters) of a webservice on the client side (client side being a vb consumer not javascript)?
Web services are method-based, so they're not designed to access properties.
But there's no reason you couldn't make GetX/SetX methods which are exposed like regular service methods - just make sure you include the [WebMethod] attribute.
As others have suggested, you will need to use get/set methods instead of properties.
As for accessing the web service from JavaScript, just specify the method name in the URL and do an XmlHttpRequest.
The only thing you can "expose" from a web service are the [WebMethod].
You might access your web service with code like the following:
Dim svc as New WebReference.MyWebService()
Dim result As Integer = svc.GetSomeInteger()
svc.SetSomeInteger(result)
Dim result2 As Integer = svc.GetSomeInteger()
You may think that you have created an instance of the web service class. You have not. You have only created an instance of the proxy class in your VB.NET code. In the above code, each call to the web service goes through the same client proxy instance, but will go to a different instance of the server-side web service class.
Even if the web service had properties, or just fields, since you would have a different instance of the web service for each call, you would have a different version of "SomeInteger" each time.

Asp.Net Ajax - Call non-static method

From client side, I need to call a server method that is not static.
For example, I got the following user control ucData (private instance of code-behind) that is Databind in the load event.
The server method I need should return ucData.IsValid(). So it can't be static
Is there a way I can do that ?
No...because there is no instance on the server to call the method on. Once the page is generated and sent to the client, there is no more context and all instances are destroyed.
Your best option is going to be to:
Create a static method
Pass that method the info needed to create the instance of the object you need
Call the method on the instance you just created
Return the results from your static method.

Resources