码迷,mamicode.com
首页 > 其他好文 > 详细

第11章 SportsStorePeta 安全性与收尾工作

时间:2015-08-01 23:21:05      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:

一、实现管理控制的安全

  修改web.config中的条目:

<authentication mode="Forms">
      <forms loginUrl="~/Account/Login" timeout="2880" >
        <credentials passwordFormat="Clear">
          <user name="admin" password="123123"/>
        </credentials>
      </forms>
    </authentication>

  1.动作过滤器进行授权

    将授权属性添加到控制器类    

 
    [Authorize]
    public class AdminController : Controller
    {
        ....
    }

  2.创建认证提供器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using SportsStorePeta.WebUI.Infrastructure.Abstract;

namespace SportsStorePeta.WebUI.Infrastructure.Concrete
{
    public class FormsAuthProvider  :IAuthProvider
    {
        public bool Authenticate(string username, string passowrd)
        {
            bool result = FormsAuthentication.Authenticate(username, passowrd);
            if (result)
            {
                FormsAuthentication.SetAuthCookie(username,false);
            }
            return result;
        }
    }
}

    注册认证提供器

  private void AddBindings()
        {
            .......
            _ninjectKernel.Bind<IOrderProcessor>().To<EmailOrderProcessor>().WithConstructorArgument("settings",emailSettings );
            //认证提供器
            _ninjectKernel.Bind<IAuthProvider>().To<FormsAuthProvider>();
        }

  3.创建Account控制器

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace SportsStorePeta.WebUI.Models
{
    public class LoginViewModel
    {
        [Required]
        public string UserName { get; set; }

        [Required]
        [DataType(DataType.Password)]
        public string Password { get; set; }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SportsStorePeta.WebUI.Infrastructure.Abstract;
using SportsStorePeta.WebUI.Models;

namespace SportsStorePeta.WebUI.Controllers
{
    public class AccountController : Controller
    {
        private IAuthProvider _authProvider;

        public AccountController(IAuthProvider auth)
        {
            _authProvider = auth;
        }

        public ViewResult Login()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Login(LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (_authProvider.Authenticate(model.UserName, model.Password))
                {
                    return Redirect(returnUrl??Url.Action("Index","Admin"));
                }
                else
                {
                    ModelState.AddModelError("","用户名或密码错误!");
                    return View();
                }
            }
            else
            {
                return View();
            }
        }

    }
}

  4.创建视图

@model SportsStorePeta.WebUI.Models.LoginViewModel

@{
    ViewBag.Title = "管理员登录";
    Layout = "~/Views/Shared/_AdminLoyout.cshtml";
}

<h2>登录</h2>
<p>后台管理请登录:</p>
@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)
    @Html.EditorForModel()
    <p><input type="submit" value="登录 "/></p>
}

  验证:数据检验过程,可以在客户端进行,

  认证:身份确认过程,必须在服务器端进行。

二、图片上传

  1.扩展数据库

  数据表添加2个字段: 

    [ImageUrl] nvarchar(MAX), 
    [ImageMimeType] varchar(50)

  2.增强域模型 

  public partial class Product : DbContextDB.Record<Product>  
    {
        [Column] public int ProductId { get; set; }
        [Column] public string Name { get; set; }
        [Column] public string Description { get; set; }
        [Column] public string Category { get; set; }
        [Column] public decimal Price { get; set; }
        [Column] public string ImageUrl { get; set; }
        [Column] public string ImageMimeType { get; set; }

    }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace SportsStorePeta.Domain.Entities
{
    public partial class ProductMetaData
    {
        [HiddenInput(DisplayValue = false)]
        public int ProductId { get; set; }

        [Display(Name = "产品名称")]
        [Required(ErrorMessage = "请输入产品名称")]
        public string Name { get; set; }

        [DataType(DataType.MultilineText)]
        [Display(Name = "描述")]
        [Required(ErrorMessage = "请输入产品描述")]
        public string Description { get; set; }

        [Display(Name = "类别")]
        [Required(ErrorMessage = "请指定产品类别")]
        public string Category { get; set; }

        [Display(Name = "价格")]
        [Required]
        [Range(0.01,Double.MaxValue,ErrorMessage = "请输入真实的价格")]
        public decimal Price { get; set; }

        [HiddenInput(DisplayValue=false)]
        public string ImageUrl { get; set; }


        [HiddenInput(DisplayValue = false)]
        public string ImageMimeType { get; set; }

    }
}

   修改PpContext.cs

            get
            {
                var products = base.Query<Product>("Select ProductId,Name,Description,Category,Price,ImageUrl,ImageMimeType from Products").AsQueryable();
                return products;
            }    

  3.创建上传用户界面和元素

  注:上传文件Form 必须设置 Post 和 new{enctype="multipart/form-data"},重载方法

@model SportsStorePeta.Domain.Entities.Product

@{
    ViewBag.Title = "Admin 编辑 "+@Model.Name;
    Layout = "~/Views/Shared/_AdminLoyout.cshtml";
}

<h2>编辑 @Model.Name</h2>
@using (Html.BeginForm("Edit","Admin",FormMethod.Post,new{enctype="multipart/form-data"}))
{
    @Html.EditorForModel()
    <div class="editor-label">图片</div>
    <div class="editor-field">
        @if (Model.ImageUrl == null)
        {
            @:没有文件
        }
        else
        {
            <img width="150" height="150" src="@Url.Content(Model.ImageUrl)" alt="images"/>
        }
        <div>上传新图片:<input type="file" accept="image/bmp,image/jpeg,image/png" name="Image"/></div>
    </div>
    <input type="submit" value="保存"/>
    @Html.ActionLink("取消并返回列表","Index")
}

  4.将图片保存到服务器

       [HttpPost]
        public ActionResult Edit(Product product,HttpPostedFileBase image)
        {
            if (ModelState.IsValid)
            {
                if (image != null)
                {
                    product.ImageMimeType = image.ContentType;
                    string path = Server.MapPath("~/Content/uploads/images/");
                    string fileName = DateTime.Now.ToString("yyyyMMddhhmmss")+"-"+Path.GetFileName(image.FileName);
                    image.SaveAs(Path.Combine(path,fileName));
                    product.ImageUrl = "~/Content/uploads/images/" + fileName;
                }
                _repository.SaveProduct(product);
                TempData["message"] = string.Format("{0} 已经保存。", product.Name);
                return RedirectToAction("Index");
            }
            else
            {
                return View(product);
            }
        }

  5.显示图片(ProductSummary.cshtml)

@model SportsStorePeta.WebUI.Models.ProductViewModel

<div class="item">
    @if (Model.ImageUrl != null)
    {
        <div style="float: left; margin-right: 20px;">
            <img width="75" height="75" src="@Url.Content(Model.ImageUrl)" alt="images"/>
        </div>
    }
    <h3>@Model.Name</h3>
    @Model.Description
    @using (Html.BeginForm("AddToCart", "Cart"))
    {
        @Html.HiddenFor(x => x.ProductId)
        @Html.Hidden("returnUrl", Request.Url.PathAndQuery)
        <input type="submit" value="加入购物车"/>
    }
    <h4>@Model.Price</h4>
</div>   
     ProductController中:
      /// <summary>
        /// 根据Product域模型集合获得视图模型集合
        /// </summary>
        /// <param name="products"></param>
        /// <returns></returns>
        private IEnumerable<ProductViewModel> GetProductViewModelListByProducts(IQueryable<Product> products)
        {
            List<ProductViewModel> productsViewModels = new List<ProductViewModel>();
            foreach (Product product in products)
            {
                ProductViewModel productViewModel = new ProductViewModel()
                {
                    ProductId = product.ProductId,
                    Name = product.Name,
                    Category = product.Category,
                    Description = product.Description,
                    Price = product.Price.ToString("C"),
                    ImageUrl = product.ImageUrl,
                    ImageMimeType = product.ImageMimeType
                };
                productsViewModels.Add(productViewModel);
            }
            return productsViewModels;
        }

源码:http://yunpan.cn/cdfd24S4Z3BBm 访问密码 5958

第11章 SportsStorePeta 安全性与收尾工作

标签:

原文地址:http://www.cnblogs.com/wjs5943283/p/4694504.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!