Quick Start Series--webapi--04 adjustment under old version MVC4

Source: Internet
Author: User

Webapi is built on the basis of MVC and WCF, the original Microsoft always like a lot of encapsulation, this time finally willing to the HTTP programming model of the relevant details exposed to us. In the previous presentation, the System.Net.Http assemblies were largely based on the later versions of. NET 4.5, while the older versions were relatively weak. Many classes and interfaces do not exist in the Webapi v1.0 (and ASP. NET MVC4), and there is some lack of support for task asynchronous programming (Apicontroller default provides asynchronous execution methods), There are some things to be aware of when using, because some old projects use the. NET 4.0 assembly, unable to upgrade and use some of the new DLLs, so some of the features need to consider themselves, this article is intended to share some of the difficulties they encountered to everyone.

    • Routing settings

It is important to note in the Global.asax file that the route of WEBAPI is to be registered prior to the MVC route, otherwise the route will be invalid.

The front-end routing address is provided using @url.httprouteurl ("Addedapi", new {controller = "Smscenterapi", action = "masstexting"}) to generate the route, There are some differences between the ways of MVC and the need to be aware.

    • Parameter binding

There are two ways of Modelbinder and Mediatypeformatter, unlike MVC (MVC uses Modelbinder to bind). The former includes binders for arrays, collections, dictionaries, simple and complex types, which are actually a serializer, The default includes 3: Json.NET Json Serializer (most used); DataContractSerializer and XmlSerializer are used to serialize XML; the last is to decode the form URL and encode the body data. These formatters are in the System.Net.Http.Formatting namespace.

Related features include: Modelbindingattribute, default binding logic, Formuriattribute, only get values from URIs, Frombodyatrribute, using mediatypeformatter media formatter, is also our most commonly used in Webapi, again to remind, must provide contenttype oh, such as "Application/json".

TIP: Model binding FAQ, Webapi Formatter formatter need to provide appropriate contenttype to work, return value through datatype settings (default is XML), must not forget content negotiation, need to pay attention to content negotiation, Attached to an example of an Ajax call, I also ate a lot of losses in this, the default formatter actually do many things oh.

Here is a strong reminder that datatype represents the return value type, contenttype is the type of the request body, bear two you two goods, content negotiation is necessary, otherwise people know how to do! In addition, this datatype= ' json ' eventually reacts to the HTTP request body as Accept:application/json,

This is useful when you are using filters to intercept and create a new Httpmessageresponse httpcontent, and the final example will cover this part of the story.

    • Filtering requests

In the past, we often put some validation logic and exception handling logic in the controller, greatly increasing the complexity of the controller, can be processed through aspect-oriented (AOP), the related base classes and interfaces provided in. NET 4.0 are as follows:

asynchronous interfaces and synchronous base classes Use
Iauthenticationfilter Authorizationfilterattribute Authentication filters can run prior to parameter binding, they plan to filter the request authentication filters that are not properly authenticated and request a controversial operation before the action filter is run, and the scenario is to authenticate the customer, for example, to obtain relevant verification information in a cookie or httphead
Iactionfilter ActionFilterAttribute The action filter takes place at parameter binding and is run after the API action method call is encapsulated, allowing the interception to complete after execution before the dispatch operation. Allows the developer to increment and replace input values and output results of the operation when the target of the filter is manipulated. If the custom binder or formatter is used to extend parsing data in a normal state, then filters can be used in some special cases
Iexceptionfilter Exceptionfilterattribute When the call operation throws an exception, the exception filter is invoked, the exception is checked, and some actions are taken, such as logging, providing a new response object to handle the exception, etc.

Tip: In MVC4, it is recommended to use the synchronous base class, which is recommended in later versions to extend the application using asynchronous interfaces.

In addition, you need to pay attention to the scope of use of the filter, including: Global, add in Filterconfig; class-level filters, by adding attributes, method level filters.

The default provides authorizeattribute to complete the underlying validation, Allowanonymousattribute provides anonymous authentication. There is also a third-party solution for OData, including Queryableattribute that can automatically support OData query syntax (such as $top, $filter, and so on).

    • Other small knowledge points

Webapi's Hosting, Includes IIS managed by System.Web.Http.WebHost.dll, configuration object is globalconfiguration, self-hosted configuration, through Mocrosoft.AspNet.WebApi.Selfhost.

The Iapiexplorer service can be obtained through Httpconfiguration.service, which is the full domain search for available services.

Tracking applications through Itracewriter, can be very convenient and ETW, Log4net, Elmah and other tracking services integration.

    • Simple sample programs, including the use of filters, jquery calls, simple verification of requests

Controller:

View Code

jquery Calls:

View Code

Checkpremissionfilter:

View Code

Smstokenhelper:

View Code

Tip:des encryption section for reference Bo Master IT partner article http://www.cnblogs.com/IT-haidong/p/4856848.html

Finally, it is very simple to add a custom moderbinder under MVC4.0, but it can help to bind the JSON data and make it easier to use. Of course, using jquery's Form.serialize (), converting the data into a form submission, and then applying the default binder is OK. Before the form has been submitted and did not seriously think about the difference between form, in fact, the form is the "&" symbol to connect the data.

View Code

In addition, the WEBAPI Study Series catalogue is as follows, welcome your reading!

Quick Start Series--webapi--01 Basics

Quick Start Series--webapi--02 Advanced

Quick Start Series--webapi--03 frame you deserve it

Quick Start Series--webapi--04 adjustment under old version MVC4

Resources:

    1. (Mei) Galloway. ASP. NET MVC 4 Advanced Programming (4th edition) [M]. Beijing: Tsinghua University Press, 2012.

Quick Start Series--webapi--04 adjustment under old version MVC4

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.