返璞归真 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.
原文: 返璞归真 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
[源码下载]

目录
相关文章
|
29天前
|
开发框架 前端开发 .NET
进入ASP .net mvc的世界
进入ASP .net mvc的世界
28 0
|
29天前
mvc.net分页查询案例——mvc-paper.css
mvc.net分页查询案例——mvc-paper.css
5 0
|
1月前
|
开发框架 中间件 .NET
C# .NET面试系列七:ASP.NET Core
## 第一部分:ASP.NET Core #### 1. 如何在 controller 中注入 service? 在.NET中,在ASP.NET Core应用程序中的Controller中注入服务通常使用<u>依赖注入(Dependency Injection)</u>来实现。以下是一些步骤,说明如何在Controller中注入服务: 1、创建服务 首先,确保你已经在应用程序中注册了服务。这通常在Startup.cs文件的ConfigureServices方法中完成。例如: ```c# services.AddScoped<IMyService, MyService>(); //
60 0
|
1月前
|
开发框架 前端开发 .NET
C# .NET面试系列六:ASP.NET MVC
<h2>ASP.NET MVC #### 1. MVC 中的 TempData\ViewBag\ViewData 区别? 在ASP.NET MVC中,TempData、ViewBag 和 ViewData 都是用于在控制器和视图之间传递数据的机制,但它们有一些区别。 <b>TempData:</b> 1、生命周期 ```c# TempData 的生命周期是短暂的,数据只在当前请求和下一次请求之间有效。一旦数据被读取,它就会被标记为已读,下一次请求时就会被清除。 ``` 2、用途 ```c# 主要用于在两个动作之间传递数据,例如在一个动作中设置 TempData,然后在重定向到另
95 5
|
3月前
|
XML 前端开发 定位技术
C#(NET Core3.1 MVC)生成站点地图(sitemap.xml)
C#(NET Core3.1 MVC)生成站点地图(sitemap.xml)
25 0
|
3月前
|
前端开发
.net core mvc获取IP地址和IP所在地(其实是百度的)
.net core mvc获取IP地址和IP所在地(其实是百度的)
123 0
|
3月前
|
开发框架 前端开发 .NET
ASP.NET CORE 3.1 MVC“指定的网络名不再可用\企图在不存在的网络连接上进行操作”的问题解决过程
ASP.NET CORE 3.1 MVC“指定的网络名不再可用\企图在不存在的网络连接上进行操作”的问题解决过程
38 0
|
8月前
|
存储 开发框架 前端开发
[回馈]ASP.NET Core MVC开发实战之商城系统(五)
经过一段时间的准备,新的一期【ASP.NET Core MVC开发实战之商城系统】已经开始,在之前的文章中,讲解了商城系统的整体功能设计,页面布局设计,环境搭建,系统配置,及首页【商品类型,banner条,友情链接,降价促销,新品爆款】,商品列表页面,商品详情等功能的开发,今天继续讲解购物车功能开发,仅供学习分享使用,如有不足之处,还请指正。
114 0
|
9月前
|
开发框架 前端开发 .NET
[回馈]ASP.NET Core MVC开发实战之商城系统(三)
[回馈]ASP.NET Core MVC开发实战之商城系统(三)
67 0
|
9月前
|
开发框架 前端开发 .NET
[回馈]ASP.NET Core MVC开发实战之商城系统(一)
[回馈]ASP.NET Core MVC开发实战之商城系统(一)
113 0