WEB APi 2.0 Advantages and features? How do I start the session state in the Web API?

Source: Internet
Author: User

Objective

Once upon a while, Microsoft based Web services technology gave the most popular XML-based Web service with the end of the. asmx extension, the service in the. NET Rage in the framework is also favored by the. NET industry peers, and a few years later it has expanded into WCF, based on the SOAP protocol, which requires some configuration changes based on the WCF standard. Nowadays, we only need the HTTP protocol and the more graceful JSON format, then we will have to have a more lightweight Web service technology. Of course, although the Web service and WCF have its limitations, but it is still widely used by many enterprises, the 1:30 will not be eliminated, there is the value of its existence.

Now that the Web API appears, the Web API is a very powerful framework that only supports HTTP protocols and is the JSON format by default, and we end up with Web service and WCF drawings that need to be configured with cumbersome configurations such as endpoint, contarcts, and so on. Web API based on resetful service lightweight and powerful, let's take a look at how the Web API is powerful and lightweight, where is its advantages and characteristics?

Advantages

Let's first look at a picture

Let's explain these advantages

Configuration

In WCF we need endpoints and contracts, but in the Web API we don't need these settings at all (super simple).

Default is reset

Unlike WCF, a service in WCF corresponds from one address to a physical file (in short: An address is mapped to a service class or a. svc file), and when the physical file removes the location or removes its effect, it is conceivable that a service address in the Web API is a reset route , and the route is mapped to a method on a controller (very flexible).

Simpler Extensible Processing PipeLine

The Web API provides a set of highly extensible message-processing pipeline mechanisms, such as Delegatehandler and Filer, which provide a mechanism for requests and responses. Handler allows us to customize error handling on the activated controller and on the controller, and it can also be configured to handle routes on different controllers. The filter contains the corresponding classes and methods on the controller before and after the method is called to allow us to run some code, such as: Action filter, exception filter and so on, while the corresponding characteristics of these filters can modify the method on the controller, Can be modified either individually or globally ( High expansion ).

Abstraction with Route

Give Web service developers a slightly abstract route, but developers can see and understand such an implementation, we can map any URL to a control method, in other words, such an abstraction does not specifically correspond to which file or which specific interface, As long as the URL corresponds to a valid controller method, we just need to do our implementation in the corresponding method ( slightly abstract route )

Characteristics

Let's continue with a picture to summarize

convention-based CRUD Action

The HTTP method is automatically mapped to the corresponding method on the controller, and through the URL of the parameters passed in the Web API will automatically match, of course, the manual may need to be simple configuration, its additions and deletions to the corresponding HTTP method of the post, GET, delete and so on.

Built-in Content negoitiation

We know that the controller on the MVC returns what data format, such as JSON or XML, needs us to display the specified return type, but the controller on the Web API only has to return the original data value, which is automatically converted to JSON or XML according to the caller's request.

Attribute Routing and Route Prefixs

Routing attributes and route prefixes are very well-defined route definitions and are associated with HTTP methods on our controllers.

Route Constraints

For specific business requirements we need different routes to constrain, such as type, value range, and routing constraints in the Web API is a great feature.

CORS Support

This cross-domain feature support is really a feast for our eyes, you can run a cross-domain request between JS applications.

Global Error Handling

In this feature, all unhandled error mechanisms are crawled to allow multiple exception handling records to be supported by the access error exception and the context Web API where the exception resides.

Summarize

From the above, the strong and flexible Web API is unmatched by WCF and Web service, in Web services technology, the simplicity of Web API and elegance has become the best service technology choice. This, of course, is the development of the needs of the Web service and the shoulders of WCF, or of the times, and we just need to understand how big the feet are and how big the shoes are.

Start Session Status Preface

Before this topic I do not know, in the "Hi Blog" in a group of friends asked to know in the Web API is not support session, said more accurate is the default does not start the session, here on a unified study, I hope you have something to gain. The session in the Web API is not dependent on system.web, and if we are going to run the Web API at ASP, we need to start the session at this point, so what do we do if we start the API in a Web API environment? There are two ways to do this, look down.

WEB API Global Startup session (i)

The following are all in the Global.asax global file.

First step (define two variables)
Private Const string " APi "  Privatestaticstringstring. Format ("~/{0}", Webapiprefix);
Second step (Gets the path of the current request)
Private BOOL iswebapirequest () {  return  HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.StartsWith (Webapiexecutepath); }
Step three (if the Web API is requested to start the session)
        protected void application_postauthorizerequest ()        {            if  (Iswebapirequest ())            {                HttpContext.Current.SetSessionStateBehavior ( System.Web.SessionState.SessionStateBehavior.Required);            }        }
Fourth step (test code)
        protected void session_start ()        {            HttpContext.Current.Session.Add ("xpy0928 " " Hi-Blog "  );             var session_value = httpcontext.current.session["xpy0928"];        }

Tests such as:

WEB API Global Startup session (II)

Before we talked about Httpcontrollerroutehandler in the Web API series, the Gethttphandler method in this class returns an instance of Httpcontrollerhandler, which is HttpHandler. This HttpHandler is the entry point into the Web API message processing pipeline, and we can implement the Irquiressionstate interface using the session on the IHttpHandler.

First step (start session)
        protected void application_postauthorizerequest ()        {            HttpContext.Current.SetSessionStateBehavior (System.Web.SessionState.SessionStateBehavior.Required);        }
Second step (custom implementation HttpHandler)
     Public class Enablesession_controllerhandler:httpcontrollerhandler, IRequiresSessionState    {        public  Enablesession_controllerhandler (routedata routedata)              base( Routedata)          {}    }
Step three (Get HttpHandler)
     Public class Enablesession_controllerhandler:httpcontrollerhandler, IRequiresSessionState    {        public  Enablesession_controllerhandler (routedata routedata)              base( Routedata)          {}    }
Fourth step (routing configuration to get custom Routehandler)
          routes. Maphttproute (               "defaultapi",               "api/{controller}/{ ID}",               new {id = urlparameter.optional}           new Enablesession_httpcontrollerroutehandler ();
Fifth step (implement custom Httpcontrollerroutehandler in the Web API configuration file)
         Public Static voidRegister (httpconfiguration config) {varHttpcontrollerroutehandler =typeof(Httpcontrollerroutehandler). GetField ("_instance", BindingFlags.Static|bindingflags.nonpublic); if(Httpcontrollerroutehandler! =NULL) {Httpcontrollerroutehandler.setvalue (NULL,                    NewLazyNewEnablesession_httpcontrollerroutehandler (),true)); } config.          Maphttpattributeroutes (); }

The following error will appear when running:

"Note" Solution: httpconfiguration.ensureinitialized exceptions caused by property routing in the Web API

Sixth step (test code)
         Public voidGet () {Objectcontext; if(Request.Properties.TryGetValue ("Ms_httpcontext", outcontext)) {                varHttpContext = Context asHttpContextBase; if(HttpContext! =NULL&& httpcontext.session! =NULL)                {                    varLastvalue = httpcontext.session["xpy0928"] as int?; httpcontext.session["xpy0928"] ="Blog Park"; varSession_value = httpcontext.session["xpy0928"]; }            }        }
Summarize

Both of these methods can be started in the Web API session, you think that simple to follow the corresponding. One problem we need to be aware of is that in the Web API, the Web API is not dependent on HttpContext, That is, HttpContext.Current is definitely null, we want to access the session or other objects need to use the properties in the Rquest object to get the value you want or to set the value.

WEB APi 2.0 Advantages and features? How do I start the session state in the Web API?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.