对一个前端使用AngularJS后端使用ASP.NET Web API项目的理解(2)
chsakell分享了一个前端使用AngularJS,后端使用ASP.NET Web API的项目。
源码: https://github.com/chsakell/spa-webapi-angularjs
文章:http://chsakell.com/2015/08/23/building-single-page-applications-using-web-api-and-angularjs-free-e-book/
这里记录下对此项目的理解。分为如下几篇:
● 对一个前端使用AngularJS后端使用ASP.NET Web API项目的理解(1)--领域、Repository、Service
● 对一个前端使用AngularJS后端使用ASP.NET Web API项目的理解(2)--依赖倒置、Bundling、视图模型验证、视图模型和领域模型映射、自定义handler
● 对一个前端使用AngularJS后端使用ASP.NET Web API项目的理解(3)--主页面布局
● 对一个前端使用AngularJS后端使用ASP.NET Web API项目的理解(4)--Movie增改查以及上传图片
依赖倒置
我们注意到经常是把接口注入到构造函数中,然后调用接口方法,如何最终让接口的实现类执行相应的方法呢?这时候就应该请出Autofac了。通过NuGet安装:Autofac ASP.NET Web API 2.2 Integration
在HomeCinema.Web中创建有关Autofac的配置类。
namespace HomeCinema.Web.App_Start
{
public class AutofacWebapiConfig
{
public static IContainer Container;
public static void Initialize(HttpConfiguration config)
{
Initialize(config, RegisterServices(new ContainerBuilder()));
} public static void Initialize(HttpConfiguration config, IContainer container)
{
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
} private static IContainer RegisterServices(ContainerBuilder builder)
{
builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); // EF HomeCinemaContext
builder.RegisterType<HomeCinemaContext>()
.As<DbContext>()
.InstancePerRequest(); builder.RegisterType<DbFactory>()
.As<IDbFactory>()
.InstancePerRequest(); builder.RegisterType<UnitOfWork>()
.As<IUnitOfWork>()
.InstancePerRequest(); builder.RegisterGeneric(typeof(EntityBaseRepository<>))
.As(typeof(IEntityBaseRepository<>))
.InstancePerRequest(); ... Container = builder.Build(); return Container;
}
}
}
再创建一个用来初始化Autofac。
namespace HomeCinema.Web.App_Start
{
public class Bootstrapper
{
public static void Run()
{
// Configure Autofac
AutofacWebapiConfig.Initialize(GlobalConfiguration.Configuration);
...
}
}
}
还需要在全局运行以上的静态方法Run.
public class Global : HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
var config = GlobalConfiguration.Configuration; ...
Bootstrapper.Run();
...
GlobalConfiguration.Configuration.EnsureInitialized();
...
}
}
配置Bundling
在ASP.NET MVC中提供了一种管理js,css文件的方法叫做Bunling,首先提供一个静态方法为BundleCollection集合添加元素。如下:
namespace HomeCinema.Web.App_Start
{
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/Vendors/modernizr.js")); bundles.Add(new ScriptBundle("~/bundles/vendors").Include(
"~/Scripts/Vendors/jquery.js",
"~/Scripts/Vendors/bootstrap.js",
"~/Scripts/Vendors/toastr.js",
"~/Scripts/Vendors/jquery.raty.js",
"~/Scripts/Vendors/respond.src.js",
"~/Scripts/Vendors/angular.js",
"~/Scripts/Vendors/angular-route.js",
"~/Scripts/Vendors/angular-cookies.js",
"~/Scripts/Vendors/angular-validator.js",
"~/Scripts/Vendors/angular-base64.js",
"~/Scripts/Vendors/angular-file-upload.js",
"~/Scripts/Vendors/angucomplete-alt.min.js",
"~/Scripts/Vendors/ui-bootstrap-tpls-0.13.1.js",
"~/Scripts/Vendors/underscore.js",
"~/Scripts/Vendors/raphael.js",
"~/Scripts/Vendors/morris.js",
"~/Scripts/Vendors/jquery.fancybox.js",
"~/Scripts/Vendors/jquery.fancybox-media.js",
"~/Scripts/Vendors/loading-bar.js"
)); bundles.Add(new ScriptBundle("~/bundles/spa").Include(
"~/Scripts/spa/modules/common.core.js",
"~/Scripts/spa/modules/common.ui.js",
"~/Scripts/spa/app.js",
"~/Scripts/spa/services/apiService.js",
"~/Scripts/spa/services/notificationService.js",
"~/Scripts/spa/services/membershipService.js",
"~/Scripts/spa/services/fileUploadService.js",
"~/Scripts/spa/layout/topBar.directive.js",
"~/Scripts/spa/layout/sideBar.directive.js",
"~/Scripts/spa/layout/customPager.directive.js",
"~/Scripts/spa/directives/rating.directive.js",
"~/Scripts/spa/directives/availableMovie.directive.js",
"~/Scripts/spa/account/loginCtrl.js",
"~/Scripts/spa/account/registerCtrl.js",
"~/Scripts/spa/home/rootCtrl.js",
"~/Scripts/spa/home/indexCtrl.js",
"~/Scripts/spa/customers/customersCtrl.js",
"~/Scripts/spa/customers/customersRegCtrl.js",
"~/Scripts/spa/customers/customerEditCtrl.js",
"~/Scripts/spa/movies/moviesCtrl.js",
"~/Scripts/spa/movies/movieAddCtrl.js",
"~/Scripts/spa/movies/movieDetailsCtrl.js",
"~/Scripts/spa/movies/movieEditCtrl.js",
"~/Scripts/spa/controllers/rentalCtrl.js",
"~/Scripts/spa/rental/rentMovieCtrl.js",
"~/Scripts/spa/rental/rentStatsCtrl.js"
)); bundles.Add(new StyleBundle("~/Content/css").Include(
"~/content/css/site.css",
"~/content/css/bootstrap.css",
"~/content/css/bootstrap-theme.css",
"~/content/css/font-awesome.css",
"~/content/css/morris.css",
"~/content/css/toastr.css",
"~/content/css/jquery.fancybox.css",
"~/content/css/loading-bar.css")); BundleTable.EnableOptimizations = false;
}
}
}
在全局中启用Bundling。
public class Global : HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
...
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
在ASP.NET MVC的视图页按如下调用Bundle中的css或js文件。
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
@Scripts.Render("~/bundles/vendors")
@Scripts.Render("~/bundles/spa")
Styles.Render方法或Scripts.Render位于"Microsoft Asp.Net Web Optimization"组件的"System.Web.Optimization"命名空间内,先通过NuGet安装:Microsoft Asp.Net Web Optimization
然后在Views文件夹的web.config中把"System.Web.Optimization"命名空间配置进去。
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="HomeCinema.Web" />
<add namespace="System.Web.Optimization" />
</namespaces>
</pages>
视图模型的验证
首先,通过NuGet安装:FluentValidation
拿Customer的视图模型来说:
namespace HomeCinema.Web.Models
{
[Bind(Exclude = "UniqueKey")]
public class CustomerViewModel : IValidatableObject
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string IdentityCard { get; set; }
public Guid UniqueKey { get; set; }
public DateTime DateOfBirth { get; set; }
public string Mobile { get; set; }
public DateTime RegistrationDate { get; set; } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var validator = new CustomerViewModelValidator();
var result = validator.Validate(this);
return result.Errors.Select(item => new ValidationResult(item.ErrorMessage, new[] { item.PropertyName }));
}
}
}
通过IValidatableObject的接口方法Validate,我们为CustomerViewModel定义了一个验证类CustomerViewModelValidator:
namespace HomeCinema.Web.Infrastructure.Validators
{
public class CustomerViewModelValidator : AbstractValidator<CustomerViewModel>
{
public CustomerViewModelValidator()
{
RuleFor(customer => customer.FirstName).NotEmpty()
.Length(, ).WithMessage("First Name must be between 1 - 100 characters"); RuleFor(customer => customer.LastName).NotEmpty()
.Length(, ).WithMessage("Last Name must be between 1 - 100 characters"); RuleFor(customer => customer.IdentityCard).NotEmpty()
.Length(, ).WithMessage("Identity Card must be between 1 - 50 characters"); RuleFor(customer => customer.DateOfBirth).NotNull()
.LessThan(DateTime.Now.AddYears(-))
.WithMessage("Customer must be at least 16 years old."); RuleFor(customer => customer.Mobile).NotEmpty().Matches(@"^\d{10}$")
.Length().WithMessage("Mobile phone must have 10 digits"); RuleFor(customer => customer.Email).NotEmpty().EmailAddress()
.WithMessage("Enter a valid Email address"); }
}
}
以上的RuleFor方法等就是FluentValidation组件的Fluent API。
视图模型和领域模型的映射
首先,通过NuGet安装:Automapper
继承AutoMapper的Profile类,用来把领域模型映射到视图模型。
namespace HomeCinema.Web.Mappings
{
public class DomainToViewModelMappingProfile : Profile
{
public override string ProfileName
{
get { return "DomainToViewModelMappings"; }
} protected override void Configure()
{
Mapper.CreateMap<Movie, MovieViewModel>()
.ForMember(vm => vm.Genre, map => map.MapFrom(m => m.Genre.Name))
.ForMember(vm => vm.GenreId, map => map.MapFrom(m => m.Genre.ID))
.ForMember(vm => vm.IsAvailable, map => map.MapFrom(m => m.Stocks.Any(s => s.IsAvailable)))
.ForMember(vm => vm.NumberOfStocks, map => map.MapFrom(m => m.Stocks.Count))
.ForMember(vm => vm.Image, map => map.MapFrom(m => string.IsNullOrEmpty(m.Image) == true ? "unknown.jpg" : m.Image)); Mapper.CreateMap<Genre, GenreViewModel>()
.ForMember(vm => vm.NumberOfMovies, map => map.MapFrom(g => g.Movies.Count()));
// code omitted
Mapper.CreateMap<Customer, CustomerViewModel>(); Mapper.CreateMap<Stock, StockViewModel>(); Mapper.CreateMap<Rental, RentalViewModel>();
}
}
}
再写一个继承AutoMapper的Profile类,用来把视图模型映射到领域模型。
namespace HomeCinema.Web.Mappings
{
public class ViewModelToDomainMappingProfile : Profile
{
public override string ProfileName
{
get { return "ViewModelToDomainMappings"; }
} protected override void Configure()
{
Mapper.CreateMap<MovieViewModel, Movie>()
//.ForMember(m => m.Image, map => map.Ignore())
.ForMember(m => m.Genre, map => map.Ignore());
}
}
}
接着定义一个有关AutoMapper的配置类:
namespace HomeCinema.Web.Mappings
{
public class AutoMapperConfiguration
{
public static void Configure()
{
Mapper.Initialize(x =>
{
x.AddProfile<DomainToViewModelMappingProfile>();
});
}
}
}
封装一个类调用AutoMapper的配置:
namespace HomeCinema.Web.App_Start
{
public class Bootstrapper
{
public static void Run()
{
// Configure Autofac
AutofacWebapiConfig.Initialize(GlobalConfiguration.Configuration);
//Configure AutoMapper
AutoMapperConfiguration.Configure();
}
}
}
最后,在全局文件中运行Run静态方法,略去。
自定义HttpMessageHandler
在System.Net.Http命名空间中定义了一个抽象类自定义HttpMessageHandler,其中定义了一个SendAsync方法,用来接收请求,返回响应,以异步的方式:
protected internal abstract Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken);
HttpMessageHandler还有一个继承类DelegatingHandler,这里,就来继承DelegatingHandler,实现自定义handler。
namespace HomeCinema.Web.MessageHandlers
{
public class HomeCinemaAuthHandler : DelegatingHandler
{
IEnumerable<string> authHeaderValues = null;
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
try
{
request.Headers.TryGetValues("Authorization",out authHeaderValues);
if(authHeaderValues == null)
return base.SendAsync(request, cancellationToken); // cross fingers var tokens = authHeaderValues.FirstOrDefault();
tokens = tokens.Replace("Basic","").Trim();
if (!string.IsNullOrEmpty(tokens))
{
byte[] data = Convert.FromBase64String(tokens);
string decodedString = Encoding.UTF8.GetString(data);
string[] tokensValues = decodedString.Split(':'); //扩展方法GetMembershipService
var membershipService = request.GetMembershipService(); var membershipCtx = membershipService.ValidateUser(tokensValues[], tokensValues[]);
if (membershipCtx.User != null)
{
IPrincipal principal = membershipCtx.Principal;
Thread.CurrentPrincipal = principal;
HttpContext.Current.User = principal;
}
else // Unauthorized access - wrong crededentials
{
var response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
var tsc = new TaskCompletionSource<HttpResponseMessage>();
tsc.SetResult(response);
return tsc.Task;
}
}
else
{
var response = new HttpResponseMessage(HttpStatusCode.Forbidden);
var tsc = new TaskCompletionSource<HttpResponseMessage>();
tsc.SetResult(response);
return tsc.Task;
}
return base.SendAsync(request, cancellationToken);
}
catch
{
var response = new HttpResponseMessage(HttpStatusCode.Forbidden);
var tsc = new TaskCompletionSource<HttpResponseMessage>();
tsc.SetResult(response);
return tsc.Task;
}
}
}
}
以上,request.GetMembershipService()方法使基于HttpRequestMessage的扩展方法,用来从依赖倒置中获取某个接口。
namespace HomeCinema.Web.Infrastructure.Extensions
{
public static class RequestMessageExtensions
{
internal static IMembershipService GetMembershipService(this HttpRequestMessage request)
{
return request.GetService<IMembershipService>();
} internal static IEntityBaseRepository<T> GetDataRepository<T>(this HttpRequestMessage request) where T : class, IEntityBase, new()
{
return request.GetService<IEntityBaseRepository<T>>();
} private static TService GetService<TService>(this HttpRequestMessage request)
{
IDependencyScope dependencyScope = request.GetDependencyScope();
TService service = (TService)dependencyScope.GetService(typeof(TService)); return service;
}
}
}
最后,在WebApi.config中配置。
namespace HomeCinema.Web
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.MessageHandlers.Add(new HomeCinemaAuthHandler()); // Web API routes
config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
待续~
对一个前端使用AngularJS后端使用ASP.NET Web API项目的理解(2)的更多相关文章
- 对一个前端使用AngularJS后端使用ASP.NET Web API项目的理解(4)
chsakell分享了一个前端使用AngularJS,后端使用ASP.NET Web API的项目. 源码: https://github.com/chsakell/spa-webapi-angula ...
- 对一个前端使用AngularJS后端使用ASP.NET Web API项目的理解(3)
chsakell分享了一个前端使用AngularJS,后端使用ASP.NET Web API的项目. 源码: https://github.com/chsakell/spa-webapi-angula ...
- 对一个前端使用AngularJS后端使用ASP.NET Web API项目的理解(1)
chsakell分享了一个前端使用AngularJS,后端使用ASP.NET Web API的项目. 源码: https://github.com/chsakell/spa-webapi-angula ...
- 购物车Demo,前端使用AngularJS,后端使用ASP.NET Web API(3)--Idetity,OWIN前后端验证
原文:购物车Demo,前端使用AngularJS,后端使用ASP.NET Web API(3)--Idetity,OWIN前后端验证 chsakell分享了前端使用AngularJS,后端使用ASP. ...
- 购物车Demo,前端使用AngularJS,后端使用ASP.NET Web API(2)--前端,以及前后端Session
原文:购物车Demo,前端使用AngularJS,后端使用ASP.NET Web API(2)--前端,以及前后端Session chsakell分享了前端使用AngularJS,后端使用ASP.NE ...
- 购物车Demo,前端使用AngularJS,后端使用ASP.NET Web API(1)--后端
原文:购物车Demo,前端使用AngularJS,后端使用ASP.NET Web API(1)--后端 chsakell分享了前端使用AngularJS,后端使用ASP.NET Web API的购物车 ...
- 对一个前端AngularJS,后端OData,ASP.NET Web API案例的理解
依然chsakell,他写了一篇前端AngularJS,后端OData,ASP.NET Web API的Demo,关于OData在ASP.NET Web API中的正删改查没有什么特别之处,但在前端调 ...
- 在ASP.NET Web API项目中使用Hangfire实现后台任务处理
当前项目中有这样一个需求:由前端用户的一个操作,需要触发到不同设备的消息推送.由于推送这个具体功能,我们采用了第三方的服务.而这个服务调用有时候可能会有延时,为此,我们希望将消息推送与用户前端操作实现 ...
- 如何创建一个Asp .Net Web Api项目
1.点击文件=>新建=>项目 2.创建一个Asp .NET Web项目 3.选择Empty,然后选中下面的MVC和Web Api,也可以直接选择Web Api选项,注意将身份验证设置为无身 ...
随机推荐
- 【逆向知识】裸函数(Naked函数)
1 说明 指定裸函数编写的函数,编译器生成不带任何多余代码. 利用此功能,可以使用内联汇编程序代码编写自己的 prolog/epilog 代码序列. 裸函数对于编写虚拟设备驱动程序特别有用. 2 练习 ...
- 数据库SQL中case when函数的用法
Case具有两种格式,简单Case函数和Case搜索函数.这两种方式,可以实现相同的功能.简单Case函数的写法相对比较简洁,但是和Case搜索函数相比,功能方面会有些限制,比如写判断式. 简单Cas ...
- 2018 ICPC 沈阳网络赛
2018 ICPC 沈阳网络赛 Call of Accepted 题目描述:求一个算式的最大值与最小值. solution 按普通算式计算方法做,只不过要同时记住最大值和最小值而已. Convex H ...
- com.alibaba.fastjson.JSONException: autoType is not support.
解决办法:https://github.com/alibaba/fastjson/wiki/enable_autotype 文摘如下: 一.添加autotype白名单 添加白名单有三种方式,三选一,如 ...
- Linux挂载qcow2格式的镜像
qcow2格式的镜像一般用于KVM/QEMU的hypervisor,当我们需要修改guest host内的一些配置而又不想启动VM时则可以通过挂载guest host进行修改. 需要安装的工具包: l ...
- Taints和Tolerations联用,将pod部署到k8s的master节点
一般,k8s的master为了保持高性能,在这个主节点上只运行一些管理必须的POD. 如果我们限于资源,或是一些监控类的pod要部署到master节点呢? 昨天遇到这个问题,按网上通用的方法,未解决, ...
- Linux系统运维笔记(五),CentOS 6.4安装java程序
Linux系统运维笔记(五),CentOS 6.4安装java程序 用eclipse编译通的java程序,现需要实施到服务器.实施步骤: 一,导出程序成jar包. 1,在主类编辑界面点右健,选 ru ...
- 【AtCoder】ARC093
C - Traveling Plan 相当于一个环,每次删掉i点到两边的距离,加上新相邻的两个点的距离 代码 #include <bits/stdc++.h> #define fi fir ...
- 桌面图形化安装的CentOS6.7中默认安装的yum不能正常使用
使用rpm -qa|grep yum,可以发现有好多关于yum的安装插件等东西... 从里面将的一些东西删除掉,只留下下面三个即可,其余的全部删除掉rpm -e yum-plugin-security ...
- python3脚本获取本机公网ip
python脚本获取本机公网ip 1.获取公网IP地址方式,访问:http://txt.go.sohu.com/ip/soip 2.代码实现 import requests import re r ...