返璞歸真 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
[源碼下載]


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM