返璞归真 asp.net mvc (13) - asp.net mvc 5.0 新特性

原文: 返璞归真 asp.net mvc (13) - asp.net mvc 5.0 新特性

[索引页]
[源码下载]


返璞归真 asp.net mvc (13) - asp.net mvc 5.0 新特性



作者:webabcd


介绍
asp.net mvc 之 asp.net mvc 5.0 新特性

  • MVC5, WebAPI2(Attribute Routing, Cross Origin Request Sharing, OData), SignalR, SPA(Single Page Application)



示例
1、简介 MVC5 的新特性
MVC50/Index.html

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

    <title>返璞归真 asp.net mvc - asp.net mvc 5.0 新特性</title>

</head>

<body>

    <h2>返璞归真 asp.net mvc - asp.net mvc 5.0 新特性 之 MVC5</h2>



    <p>

        现在可以继承 System.Web.Http.AuthorizeAttribute, ExceptionFilterAttribute 了

    </p>



    <p>

        内置支持 oauth 到一些知名网站,代码参见 App_Start/Startup.Auth.cs;效果参见 http://localhost:26659(进去后点击登录)

    </p>

</body>

</html>

MVC50/App_Start/Startup.Auth.cs

using Microsoft.AspNet.Identity;

using Microsoft.Owin;

using Microsoft.Owin.Security.Cookies;

using Owin;



namespace MVC50

{

    public partial class Startup

    {

        // 有关配置身份验证的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkId=301864

        public void ConfigureAuth(IAppBuilder app)

        {

            // 使应用程序可以使用 Cookie 来存储已登录用户的信息

            app.UseCookieAuthentication(new CookieAuthenticationOptions

            {

                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,

                LoginPath = new PathString("/Account/Login")

            });

            // Use a cookie to temporarily store information about a user logging in with a third party login provider

            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);



            // 取消注释以下行可允许使用第三方登录提供程序登录

            //app.UseMicrosoftAccountAuthentication(

            //    clientId: "",

            //    clientSecret: "");



            //app.UseTwitterAuthentication(

            //   consumerKey: "",

            //   consumerSecret: "");



            //app.UseFacebookAuthentication(

            //   appId: "",

            //   appSecret: "");



            // 支持使用 google 账户登录

            app.UseGoogleAuthentication();

        }

    }

}


2、简介 WebAPI2 的新特性
WebAPI2/Index.html

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

    <title>返璞归真 asp.net mvc - asp.net mvc 5.0 新特性</title>

</head>

<body>

    <h2>返璞归真 asp.net mvc - asp.net mvc 5.0 新特性 之 WebAPI2</h2>



    <p>

        <a href="AttributeRouting.html" target="_blank">WebAPI2 - Attribute Routing</a>

    </p>



    <p>

        <a href="CORS.html" target="_blank">WebAPI2 - Cross Origin Request Sharing</a>

    </p>



    <p>

        <a href="OData.html" target="_blank">WebAPI2 - OData</a>

    </p>    

</body>

</html>


2.1 演示 WebAPI2 - Attribute Routing
WebAPI2/Controllers/AttributeRoutingController.cs

/*

 * 用于演示 Attribute Routing 特性

 */



using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Net.Http;

using System.Web.Http;



namespace WebAPI2.Controllers

{

    public class AttributeRoutingController : ApiController

    {

        // 经典路由方式(路由配置来自 RouteConfig)

        // http://localhost:26700/api/AttributeRouting?name=webabcd

        public string Get(string name)

        {

            string result = "Hello: " + name + " (经典路由)";



            return result;

        }



        // Attribute Routing 路由方式,让 Action 可以有自己自定义的路由方式

        // http://localhost:26700/hello/webabcd

        [Route("hello/{name}")]

        public string Get2(string name)

        {

            string result = "Hello: " + name + " (Attribute Routing)";

            

            return result;

        }

    }

}

WebAPI2/AttributeRouting.html

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

    <script src="Scripts/jquery-1.10.2.js"></script>

    <title>Attribute Routing</title>

</head>

<body>

    <script type="text/javascript">



        // 调用经典路由方式的 api

        var result = $.get("http://localhost:26700/api/AttributeRouting?name=webabcd", function (msg) {

            alert(msg);

        });



        // 调用 Attribute Routing 路由方式的 api

        var result = $.get("http://localhost:26700/hello/webabcd", function (msg) {

            alert(msg);

        });



    </script>

</body>

</html>


2.2 演示 WebAPI2 - Cross Origin Request Sharing
WebAPI2/Controllers/CORSController.cs

/*

 * 演示 web api 对 cors(Cross Origin Resource Sharing) 的支持

 * 

 * 注:请先行参见 WebApiConfig.cs

 */



using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Net.Http;

using System.Web.Http;



namespace WebAPI2.Controllers

{

    public class CORSController : ApiController

    {

        public string Get()

        {

            return "Hello: Cross Origin Resource Sharing";

        }

    }

}

WebAPI2/App_Start/WebApiConfig.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web.Http;



namespace WebAPI2

{

    public static class WebApiConfig

    {

        public static void Register(HttpConfiguration config)

        {

            // Web API configuration and services



            // Web API routes

            config.MapHttpAttributeRoutes();



            config.Routes.MapHttpRoute(

                name: "DefaultApi",

                routeTemplate: "api/{controller}/{id}",

                defaults: new { id = RouteParameter.Optional }

            );





            // nuget 中搜索 ASP.NET Cross-Origin Support,然后安装

            // 使本 api 支持 cors

            var cors = new System.Web.Http.Cors.EnableCorsAttribute("*", "*", "*");

            config.EnableCors(cors);





            // nuget 中搜索 ASP.NET Web API OData

            // 使本 api 支持 odata 查询

            config.EnableQuerySupport();

        }

    }

}

WebAPI2/CORS.html

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <script src="Scripts/jquery-1.10.2.js"></script>

    <title>Cross Origin Request Sharing</title>

</head>

<body>

    <script type="text/javascript">



        if (jQuery.support.cors) {

            jQuery.support.cors = true;

            var result = $.get("http://localhost:26700/api/cors", function (msg) {

                alert(msg);

            });

        }

        else {

            alert("浏览器不支持 cors");

        }



        /*

         * cors:全称 Cross Origin Resource Sharing,用于支持 ajax 跨域调用,支持此协议的的浏览器有 Internet Explorer 8+,Firefox 3.5+,Safari 4+ 和 Chrome 等

         * 

         * 测试场景:要把客户端与服务端配置为不同的域名

         *

         * 本例可以通过 ajax 跨域调用 api/cors 接口,会发现如下效果

         * 1、请求头中会出现 Origin: http://xxx.com.cn (此域名为 host 此客户端的域名)

         * 2、响应头中会出现 Access-Control-Allow-Origin: *

         *

         * 另:关于 cors 协议的更多详细内容网上搜一下即可

         */

        

    </script>

</body>

</html>


2.3 演示 WebAPI2 - OData
WebAPI2/Controllers/ODataController.cs

/*

 * 演示如何让 web api 支持 odata 协议

 * 

 * 注:请先行参见 WebApiConfig.cs

 */



using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Net.Http;

using System.Web.Http;

using System.Web.Http.OData.Query;



namespace WebAPI2.Controllers

{

    public class ODataController : ApiController

    {

        // 有很多 attribute 可以设置,以下仅举 2 例,更多详细内容参见文档

        // [Queryable(AllowedQueryOptions = AllowedQueryOptions.Skip | AllowedQueryOptions.Top)] // 仅支持 skip 查询和 top 查询

        // [Queryable(MaxTop = 100)] // 指定 top 参数的最大值为 100



        public IQueryable Get()

        {

            List<Product> products = new List<Product>();



            Random random = new Random();

            for (int i = 0; i < 1000; i++)

            {

                Product product = new Product();

                product.ProductId = i;

                product.Name = i.ToString().PadLeft(10, '0');

                product.Price = random.Next(100, 1000);



                products.Add(product);

            }



            return products.AsQueryable();

        }

    }



    public class Product

    {

        public int ProductId { get; set; }

        public string Name { get; set; }

        public int Price { get; set; }

    }

}

WebAPI2/App_Start/WebApiConfig.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web.Http;



namespace WebAPI2

{

    public static class WebApiConfig

    {

        public static void Register(HttpConfiguration config)

        {

            // Web API configuration and services



            // Web API routes

            config.MapHttpAttributeRoutes();



            config.Routes.MapHttpRoute(

                name: "DefaultApi",

                routeTemplate: "api/{controller}/{id}",

                defaults: new { id = RouteParameter.Optional }

            );





            // nuget 中搜索 ASP.NET Cross-Origin Support,然后安装

            // 使本 api 支持 cors

            var cors = new System.Web.Http.Cors.EnableCorsAttribute("*", "*", "*");

            config.EnableCors(cors);





            // nuget 中搜索 ASP.NET Web API OData

            // 使本 api 支持 odata 查询

            config.EnableQuerySupport();

        }

    }

}

WebAPI2/OData.html

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

    <script src="Scripts/jquery-1.10.2.js"></script>

    <title>OData</title>

</head>

<body>

    <script type="text/javascript">



        var result = $.get("http://localhost:26700/api/odata?$top=2", function (msg) {

            alert(msg[0].ProductId);

        });



        var result = $.get("http://localhost:26700/api/odata?$filter=ProductId eq 100", function (msg) {

            alert(msg[0].ProductId);

        });



        // $select 就是 WebAPI2 中新增的查询参数之一

        var result = $.get("http://localhost:26700/api/odata?$filter=ProductId eq 100&$select=Name", function (msg) {

            alert(msg[0].ProductId);

            alert(msg[0].Name);

        });



    </script>

</body>

</html>

 
3、简介 SignalR 的特性
SignalR/Index.html

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>实时通信 - SignalR</title>

</head>

<body>

    <h2>实时通信 - SignalR</h2>



    <p>

         SignalR(可以在 nuget 中安装),支持 ajax 长轮询和 WebSocket,更多内容参见:http://www.asp.net/signalr

    </p>

</body>

</html>


4、简介 SPA(Single Page Application) 的特性
SPA/Index.html

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>返璞归真 asp.net mvc - asp.net mvc 5.0 新特性</title>

</head>

<body>

    <h2>返璞归真 asp.net mvc - asp.net mvc 5.0 新特性 之 SPA(Single Page Application)</h2>



    <p>

        knockout.js - 用于支持 MVVM 模式,有效实现 js 和 html 的分离

    </p>



    <p>

        modernizr.js - 用来检测浏览器功能支持情况的 JavaScript 库

    </p>



    <p>

        respond.js - 目标是使得那些不支持 CSS3 Media Queryes 特性的浏览器能够支持

    </p>

</body>

</html>



OK
[源码下载]

你可能感兴趣的:(asp.net)