[Index page]
[Download source code]
The new feature of asp.net mvc (11)-asp.net mvc 4.0 is a self-hosted Web API. WebForm provides Web APIs to upload files through Web APIs ,. more convenient asynchronous operations brought about by net 4.5
Author: webabcd
Introduction
Asp.net mvc-New Features of asp.net mvc 4.0-Web API
- Self-hosted web APIs
- Host to iis and provide web api service through WebForm
- Upload files through Web APIs
- . Net 4.5 provides more convenient asynchronous operations
Example
1. Self-hosted Web API demo
WebApiSelfHost/Program. cs
/** Self-host web api demo ** test address: http: // localhost: 123/api/hello */using System; using System. collections. generic; using System. linq; using System. net. http; using System. text; using System. web. http; using System. web. http. selfHost; namespace WebApiSelfHost {// web api public class HelloController: ApiController {public string Get () {return "hello: webabcd ";}} class Program {static readonly Uri _ baseAddress = new Uri ("http: // localhost: 123/"); static void Main (string [] args) {HttpSelfHostServer server = null; try {// configure a self-Host http service HttpSelfHostConfiguration config = new HttpSelfHostConfiguration (_ baseAddress); // configure the http service route config. routes. mapHttpRoute (name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new {id = RouteParameter. optional}); // create http Service server = new HttpSelfHostServer (config); // start listening to server. openAsync (). wait (); // stop listening // server. closeAsync (). wait (); Console. writeLine ("Listening on" + _ baseAddress); Console. readLine ();} catch (Exception ex) {Console. writeLine (ex. toString (); Console. readLine ();}}}}
2. demonstrate how to provide web api service in WebForm
Global. asax. cs
Using System; using System. collections. generic; using System. linq; using System. web; using System. web. routing; using System. web. security; using System. web. sessionState; using System. web. http; namespace WebApiWebFormHost {public class Global: System. web. httpApplication {protected void Application_Start (object sender, EventArgs e) {// configure the route RouteTable. routes. mapHttpRoute (name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new {id = RouteParameter. optional });}}}
HelloController. cs
/** Host to iis and provide web api service through WebForm ** test address: http: // localhost: 4723/api/hello */using System; using System. collections. generic; using System. data; using System. linq; using System. net; using System. net. http; using System. web. http; namespace WebApiWebFormHost {public class HelloController: ApiController {public IEnumerable <string> Get () {string [] names = {"webabcd", "webabcd2", "webabcd3 "}; return names ;}}}
3. demonstrate how to upload files through web APIs
WebApiWebFormHost/UploadFileController. cs
/** Upload a file through the web api */using System; using System. collections. generic; using System. linq; using System. net; using System. net. http; using System. threading. tasks; using System. web. http; namespace MVC40.Controllers {public class UploadFileController: ApiController {public async Task <string> Post () {// check whether multipart/form-data if (! Request. content. isMimeMultipartContent ("form-data") throw new HttpResponseException (HttpStatusCode. unsupportedMediaType); // sets the upload directory var provider = new MultipartFormDataStreamProvider (@ "c: \ temp"); // receives data and saves the file var bodyparts = await Request. content. readAsMultipartAsync (provider); string result = ""; // obtain the form data result + = "formData txtName:" + bodyparts. formData ["txtName"]; result + = "<br/>"; // get file data result + = "fileData headers:" + bodyparts. fileData [0]. headers; // result + = "<br/>"; result + = "fileData localFileName:" + bodyparts. fileData [0]. localFileName; // The address for saving the file on the server. If necessary, rename or move return result ;}}}
WebApiWebFormHost/UploadDemo. cshtml
@ {Layout = null ;}<! DOCTYPE html>
4. More convenient asynchronous operations brought about by. net 4.5
AsyncController. cs
/** Demonstrate how to use the new features of. net 4.5 to implement asynchronous operations ** what scenarios require asynchronous operations? * Asynchronous operations should be used for long task execution time due to disk I/O or network I/O, if the task runs for a long time because of cpu consumption, synchronous operations should be used (at this time, asynchronous operations will not improve any problem) * What is the principle? * On the Web server ,. NET Framework maintains a service for ASP. NET Request thread pool. NET Framework maintenance for service ASP. NET Request thread pool is called as "specific thread pool") * When a synchronization operation is performed, if the utilization of a specific thread pool is full, no service will be provided * When an asynchronous operation is performed: * 1. A request is sent, and a thread from a specific thread pool processes the request * 2. Start another thread in a non-specific thread pool to process asynchronous operations, at this time, the thread processing this request will be empty and will not be blocked. It can continue to process other requests * 3. After the asynchronous operation is completed, returns the request result */using System; using System from any idle thread in the specified thread pool. collections. generic; using System. linq; using System. net; using System. net. http; using System. threading. tasks; using System. web. http; namespace MVC40.Controllers {public class AsyncController: ApiController {public async Task <string> Get () {return await GetData ();} [NonAction] public async Task <string> GetData () {await Task. delay (10*1000); return "long-time task execution completed ";}}}
OK
[Download source code]