总计结余数,MVC自定义验证Authorize

有三个网上朋友问及,在SQL中,总括每一笔的多余数。他提供的截图表明:
997755.com澳门葡京 1

前段时期,平素有练习ASP.NET MVC与Web
API交互,接下去,Insus.NET再做一些城门失火的勤学苦练,Web
API与公事操作,如POST文件至Web API,更新或是删除等。

前些时间,一直有演习ASP.NET MVC与Web
API交互,接下去,Insus.NET再做一些连锁的练习,Web
API与公事操作,如POST文件至Web API,更新或是删除等。

今日Insus.NET有在数据库完成过对某一字段举行加密码与解密《利用EncryptByPassPhrase和DecryptByPass玻璃沙滩se对MS
SQLServer某一字段时行加密和平解决密》[

 

不管怎样,先在数据库成立一张表,用来存款和储蓄上传的公文。本实例中是把文件存储过数据库的。

不顾,先在数据库成立一张表,用来囤积上传的文件。本实例中是把公文存款和储蓄过数据库的。

](
MVC达成自定义验证Authorize Attribute。

997755.com澳门葡京 2

997755.com澳门葡京 3

997755.com澳门葡京 4

福寿绵绵此前,Insus.NET对usp_Users_VeryLoginVerify修改一下,改为更加好理解与利用:
997755.com澳门葡京 5

 

997755.com澳门葡京 6997755.com澳门葡京 7

997755.com澳门葡京 8997755.com澳门葡京 9

 

总计结余数,MVC自定义验证Authorize。完结这些功用,关键是赢得前一笔记录eqty字段的值。

CREATE TABLE ApiFileDemo
(
    [Afd_nbr] INT IDENTITY(1,1) PRIMARY KEY NOT NULL,
    [Picture] [image] NULL,
    [PictureType] [nvarchar](30) NULL,
    [FileExtension] [nvarchar](10) NULL
)
GO

CREATE PROCEDURE [dbo].[usp_ApiFileDemo_Insert]
(    
    @Picture IMAGE,
    @PictureType NVARCHAR(30),
    @FileExtension NVARCHAR(10)
)
AS
INSERT INTO [dbo].[ApiFileDemo] ([Picture],[PictureType],[FileExtension]) VALUES (@Picture,@PictureType,@FileExtension)
GO

CREATE PROCEDURE [dbo].[usp_ApiFileDemo_Update]
(
    @Afd_nbr INT,
    @Picture IMAGE,
    @PictureType NVARCHAR(30),
    @FileExtension NVARCHAR(10)
)
AS
UPDATE [dbo].[ApiFileDemo]  SET [Picture] = @Picture,[PictureType] = @PictureType,[FileExtension] = @FileExtension WHERE [Afd_nbr] = @Afd_nbr
GO

CREATE PROCEDURE [dbo].[usp_ApiFileDemo_Delte]
(
    @Afd_nbr INT
)
AS
DELETE FROM [dbo].[ApiFileDemo] WHERE [Afd_nbr] = @Afd_nbr
GO
CREATE TABLE ApiFileDemo
(
    [Afd_nbr] INT IDENTITY(1,1) PRIMARY KEY NOT NULL,
    [Picture] [image] NULL,
    [PictureType] [nvarchar](30) NULL,
    [FileExtension] [nvarchar](10) NULL
)
GO

CREATE PROCEDURE [dbo].[usp_ApiFileDemo_Insert]
(    
    @Picture IMAGE,
    @PictureType NVARCHAR(30),
    @FileExtension NVARCHAR(10)
)
AS
INSERT INTO [dbo].[ApiFileDemo] ([Picture],[PictureType],[FileExtension]) VALUES (@Picture,@PictureType,@FileExtension)
GO

CREATE PROCEDURE [dbo].[usp_ApiFileDemo_Update]
(
    @Afd_nbr INT,
    @Picture IMAGE,
    @PictureType NVARCHAR(30),
    @FileExtension NVARCHAR(10)
)
AS
UPDATE [dbo].[ApiFileDemo]  SET [Picture] = @Picture,[PictureType] = @PictureType,[FileExtension] = @FileExtension WHERE [Afd_nbr] = @Afd_nbr
GO

CREATE PROCEDURE [dbo].[usp_ApiFileDemo_Delte]
(
    @Afd_nbr INT
)
AS
DELETE FROM [dbo].[ApiFileDemo] WHERE [Afd_nbr] = @Afd_nbr
GO

997755.com澳门葡京 10997755.com澳门葡京 11

上边Insus.NET尝试写一下。使用最轻松易行的办法,就是循环每一笔记录。然后能够测算qty加上前一笔的eqty。

Source Code

Source Code

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[usp_Users_VeryLoginVerify]
(
    @U_nbr NVARCHAR(20),
    @pwd NVARCHAR(100)
)
AS
BEGIN    
    DECLARE @errmsg NVARCHAR(50) = N'用户名或密码错误。'

    IF NOT EXISTS(SELECT TOP 1 1 FROM [dbo].[Users] WHERE [U_nbr] = @U_nbr)
    BEGIN    
        RAISERROR(@errmsg,16,1)
        RETURN
    END

    SELECT [U_nbr] AS [Account] FROM [dbo].[Users] WHERE [U_nbr] = @U_nbr AND CONVERT(NVARCHAR(100),DECRYPTBYPASSPHRASE('insus#sec!%y',[Pwd]))  = @pwd  

    IF @@ROWCOUNT <= 0
    BEGIN    
        RAISERROR(@errmsg,16,1)
        RETURN
    END
END

创建一个目前表存储原数:
997755.com澳门葡京 12

写到那里,开掘少了一个存款和储蓄进度,正是赢得某一张图纸的:
997755.com澳门葡京 13

写到那里,开掘少了二个存款和储蓄进程,便是得到某一张图纸的:
997755.com澳门葡京 14

Source Code

997755.com澳门葡京 15997755.com澳门葡京 16

997755.com澳门葡京 17997755.com澳门葡京 18

997755.com澳门葡京 19997755.com澳门葡京 20

 

CREATE TABLE #tt
(
  [empid] char(3),
  [fdate] date,
  [qty] int
)

INSERT INTO #tt([empid],[fdate],[qty]) VALUES('100','2018-01-01',100)
INSERT INTO #tt([empid],[fdate],[qty]) VALUES('100','2018-01-01',100)
INSERT INTO #tt([empid],[fdate],[qty]) VALUES('100','2018-01-01',120)
INSERT INTO #tt([empid],[fdate],[qty]) VALUES('100','2018-01-01',145)
INSERT INTO #tt([empid],[fdate],[qty]) VALUES('100','2018-01-02',30)
INSERT INTO #tt([empid],[fdate],[qty]) VALUES('100','2018-01-02',150)
INSERT INTO #tt([empid],[fdate],[qty]) VALUES('100','2018-01-02',160)
INSERT INTO #tt([empid],[fdate],[qty]) VALUES('100','2018-01-02',170)
INSERT INTO #tt([empid],[fdate],[qty]) VALUES('100','2018-01-02',121)
INSERT INTO #tt([empid],[fdate],[qty]) VALUES('100','2018-01-02',106)
CREATE PROCEDURE [dbo].[usp_ApiFileDemo_GetByPrimarykey]
(
    @Afd_nbr INT
)
AS
SELECT [Afd_nbr],[Picture],[PictureType],[FileExtension] FROM [dbo].[ApiFileDemo] WHERE [Afd_nbr] = @Afd_nbr
GO
CREATE PROCEDURE [dbo].[usp_ApiFileDemo_GetByPrimarykey]
(
    @Afd_nbr INT
)
AS
SELECT [Afd_nbr],[Picture],[PictureType],[FileExtension] FROM [dbo].[ApiFileDemo] WHERE [Afd_nbr] = @Afd_nbr
GO

OK,上面是数据库方面。
收受你必要在ASP.NET MVC写程序:

Source Code

Source Code

Source Code

选择Cookie来囤积登六以及表达消息,写一个Cookie连串:
997755.com澳门葡京 21

 

 
接下去,我们能够布置Web
API接口,待完毕了,发布至网络,别的客户端就能够操作了。

 
接下去,大家得以设计Web
API接口,待实现了,发表至英特网,别的客户端就足以操作了。

 

我们早先拍卖,创设此外三个权且表,原始表相似,不过要求加多3个字段,id和eqty。在这之中id是自然拉长的identity(1,壹)。

依照数量库表,可以在API项目中,创设Model:
997755.com澳门葡京 22

据书上说数据库表,可以在API项目中,成立Model:
997755.com澳门葡京 23

997755.com澳门葡京 24997755.com澳门葡京 25

还索要把原本数据搬到此新建的一时半刻表中:
997755.com澳门葡京 26

997755.com澳门葡京 27997755.com澳门葡京 28

997755.com澳门葡京 29997755.com澳门葡京 30

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

namespace Insus.NET.Utilities
{
    public abstract class CookieBase
    {
        private static HttpResponse Response
        {
            get
            {
                return HttpContext.Current.Response;
            }
        }

        private static HttpRequest Request
        {
            get
            {
                return HttpContext.Current.Request;
            }
        }

        public static HttpCookie Cookie
        {
            get
            {
                return Request.Cookies["CookieBase"] as HttpCookie;
            }
            set
            {
                if (Request.Cookies["CookieBase"] != null)
                {
                    Request.Cookies.Remove("CookieBase");
                }
                Response.Cookies.Add(value);
            }
        }

        public static HttpCookie NewCookie
        {
            get
            {
                return new HttpCookie("CookieBase");
            }
        }

        public static void RemoveCookie()
        {
            if (Cookie == null)
                Response.Cookies.Remove("CookieBase");
            else
                Response.Cookies["CookieBase"].Expires = DateTime.Now.AddDays(-1);
        }       
    }
}

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Insus.NET.Models
{
    public class File
    {
        public int Afd_nbr { get; set; }

        public byte[] Picture { get; set; }

        public string PictureType { get; set; }

        public string FileExtension { get; set; }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Insus.NET.Models
{
    public class File
    {
        public int Afd_nbr { get; set; }

        public byte[] Picture { get; set; }

        public string PictureType { get; set; }

        public string FileExtension { get; set; }
    }
}

Source Code

997755.com澳门葡京 31997755.com澳门葡京 32

Source Code

Source Code

 
骨子里上边这些CookeBase.cs是叁个能积累多目的的会集类。在真的的先后中,你想囤积什么新闻,能够写3个如上边包车型地铁类来操作:
997755.com澳门葡京 33

CREATE TABLE #ttt
(
    [id] int identity(1,1),
    [empid] char(3),
    [fdate] date,
    [qty] int, 
    [eqty] int
)

INSERT INTO #ttt([empid],[fdate],[qty]) SELECT  [empid],[fdate],[qty]  FROM #tt

写好model之后,还要求为API写二个实体,这些目标只是让程序与数据库实行交互。获取与存款和储蓄等操作:
997755.com澳门葡京 34

写好model之后,还需求为API写3个实体,那么些目的只是让程序与数据库举行交互。获取与存储等操作:
997755.com澳门葡京 35

 

Source Code

997755.com澳门葡京 36997755.com澳门葡京 37

997755.com澳门葡京 38997755.com澳门葡京 39

997755.com澳门葡京 40997755.com澳门葡京 41

 

using Insus.NET.DataBases;
using Insus.NET.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Insus.NET;

namespace Insus.NET.Entities
{
    public class FileEntity
    {
        BizSP sp = new BizSP();
        public DataTable GetFileByPrimarykey(File f)
        {
            List<Parameter> param = new List<Parameter>() {
                                    new Parameter("@Afd_nbr", SqlDbType.Int,4,f.Afd_nbr)
            };
            sp.ConnectionString = DB.ConnectionString;
            sp.Parameters = param;
            sp.ProcedureName = "usp_ApiFileDemo_GetByPrimarykey";
            return sp.ExecuteDataSet().Tables[0];
        }

        public void Insert(File f)
        {
            List<Parameter> param = new List<Parameter>() {
                                    new Parameter("@Picture", SqlDbType.Image,-1,f.Picture),
                                    new Parameter("@PictureType",SqlDbType.NVarChar,-1,f.PictureType),
                                    new Parameter("@FileExtension",SqlDbType.NVarChar,-1,f.FileExtension)
            };
            sp.ConnectionString = DB.ConnectionString;
            sp.Parameters = param;
            sp.ProcedureName = "usp_ApiFileDemo_Insert";
            sp.Execute();
        }

        public void Update(File f)
        {
            List<Parameter> param = new List<Parameter>() {
                                    new Parameter("@Afd_nbr", SqlDbType.Int,4,f.Afd_nbr),
                                    new Parameter("@Picture", SqlDbType.Image,-1,f.Picture),
                                    new Parameter("@PictureType",SqlDbType.NVarChar,-1,f.PictureType),
                                    new Parameter("@FileExtension",SqlDbType.NVarChar,-1,f.FileExtension)
            };
            sp.ConnectionString = DB.ConnectionString;
            sp.Parameters = param;
            sp.ProcedureName = "usp_ApiFileDemo_Update";
            sp.Execute();
        }

        public void Delete(File f)
        {
            List<Parameter> param = new List<Parameter>() {
                                    new Parameter("@Afd_nbr", SqlDbType.Int,4,f.Afd_nbr)
            };
            sp.ConnectionString = DB.ConnectionString;
            sp.Parameters = param;
            sp.ProcedureName = "usp_ApiFileDemo_Delte";
            sp.Execute();
        }
    }
}
using Insus.NET.DataBases;
using Insus.NET.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Insus.NET;

namespace Insus.NET.Entities
{
    public class FileEntity
    {
        BizSP sp = new BizSP();
        public DataTable GetFileByPrimarykey(File f)
        {
            List<Parameter> param = new List<Parameter>() {
                                    new Parameter("@Afd_nbr", SqlDbType.Int,4,f.Afd_nbr)
            };
            sp.ConnectionString = DB.ConnectionString;
            sp.Parameters = param;
            sp.ProcedureName = "usp_ApiFileDemo_GetByPrimarykey";
            return sp.ExecuteDataSet().Tables[0];
        }

        public void Insert(File f)
        {
            List<Parameter> param = new List<Parameter>() {
                                    new Parameter("@Picture", SqlDbType.Image,-1,f.Picture),
                                    new Parameter("@PictureType",SqlDbType.NVarChar,-1,f.PictureType),
                                    new Parameter("@FileExtension",SqlDbType.NVarChar,-1,f.FileExtension)
            };
            sp.ConnectionString = DB.ConnectionString;
            sp.Parameters = param;
            sp.ProcedureName = "usp_ApiFileDemo_Insert";
            sp.Execute();
        }

        public void Update(File f)
        {
            List<Parameter> param = new List<Parameter>() {
                                    new Parameter("@Afd_nbr", SqlDbType.Int,4,f.Afd_nbr),
                                    new Parameter("@Picture", SqlDbType.Image,-1,f.Picture),
                                    new Parameter("@PictureType",SqlDbType.NVarChar,-1,f.PictureType),
                                    new Parameter("@FileExtension",SqlDbType.NVarChar,-1,f.FileExtension)
            };
            sp.ConnectionString = DB.ConnectionString;
            sp.Parameters = param;
            sp.ProcedureName = "usp_ApiFileDemo_Update";
            sp.Execute();
        }

        public void Delete(File f)
        {
            List<Parameter> param = new List<Parameter>() {
                                    new Parameter("@Afd_nbr", SqlDbType.Int,4,f.Afd_nbr)
            };
            sp.ConnectionString = DB.ConnectionString;
            sp.Parameters = param;
            sp.ProcedureName = "usp_ApiFileDemo_Delte";
            sp.Execute();
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace Insus.NET.Utilities
{
   public class SecurityBase
    {
        public static bool IsAuthorized
        {
            get
            {
                return CookieBase.Cookie == null ? false : bool.Parse(CookieBase.Cookie.Values["IsAuthorized"]);
            }
            set
            {
                HttpCookie httpCookie = CookieBase.Cookie == null ? CookieBase.NewCookie : CookieBase.Cookie;
                httpCookie.Values["IsAuthorized"] = value.ToString();
                CookieBase.Cookie = httpCookie;
            }
        }

        public static string UserName
        {
            get
            {
                return CookieBase.Cookie == null ? string.Empty : CookieBase.Cookie.Values["UserName"];
            }
            set
            {
                HttpCookie httpCookie = CookieBase.Cookie == null ? CookieBase.NewCookie : CookieBase.Cookie;
                httpCookie.Values["UserName"] = value;
                CookieBase.Cookie = httpCookie;
            }
        }

        public static void RemoveCooke()
        {
            CookieBase.RemoveCookie();
        }
    }
}

接下去,Insus.NET写了三个储存过程,方法如下:
997755.com澳门葡京 42

Source Code

Source Code

Source Code

 

 

 

接下去,大家要求成立2个证实过滤器:
997755.com澳门葡京 43

997755.com澳门葡京 44997755.com澳门葡京 45

下边包车型客车操纵器FileController,就是为客户端访问的接口,这一个项目,它是传承了ApiController。
997755.com澳门葡京 46

下边包车型大巴调节器FileController,便是为客户端访问的接口,这一个类型,它是一而再了ApiController。
997755.com澳门葡京 47

997755.com澳门葡京 48997755.com澳门葡京 49

DECLARE @r int = 1,@rs INT = 0
SELECT @rs = MAX([empid]) FROM #ttt

WHILE @r <= @rs 
BEGIN    
    IF (@r = 1 )
        UPDATE #ttt SET [eqty] = [qty] WHERE [id] = @r --处理第一笔记录
    ELSE
    BEGIN
        DECLARE @eqty INT 
        SELECT @eqty = [eqty] FROM #ttt WHERE [id] = @r - 1  --获取前一笔的结余数

        UPDATE #ttt SET [eqty] = [qty] + @eqty  WHERE [id] = @r  --计算后更新当前记录的eqty字段值。
    END    

    SET @r = @r+ 1
END
GO

 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Insus.NET.Utilities;
using System.Web.Routing;

namespace Insus.NET.Attributes
{
    public class SecurityAuthorizeAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            return SecurityBase.IsAuthorized;
        }

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            string actionName = filterContext.ActionDescriptor.ActionName;           
            base.OnAuthorization(filterContext);
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            var routeValue = new RouteValueDictionary {
                { "Controller", "Home"},
                { "Action", "Index"}
            };
            filterContext.Result = new RedirectToRouteResult(routeValue);
        }
    }
}

Source Code

997755.com澳门葡京 50997755.com澳门葡京 51

997755.com澳门葡京 52997755.com澳门葡京 53

Source Code

 

using Insus.NET.Entities;
using Insus.NET.ExtendMethods;
using Insus.NET.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace Insus.NET.Controllers
{
    public class FileController : ApiController
    {
        // GET: File
        FileEntity fe = new FileEntity();

        // GET: ApiFileDemo

        [HttpGet]
        public string Get(int id)
        {
            File f = new File();
            f.Afd_nbr = id;
            return fe.GetFileByPrimarykey(f).ToJson();
        }

        [HttpPost]
        public void Post(File f)
        {
            fe.Insert(f);
        }

        [HttpPut]
        public void Put(File f)
        {
            fe.Update(f);
        }

        [HttpDelete]
        public void Delete(File f)
        {
            fe.Delete(f);
        }

        [HttpDelete]
        public void Delete(int id)
        {
            File f = new File();
            f.Afd_nbr = id;
            fe.Delete(f);
        }
    }
}
using Insus.NET.Entities;
using Insus.NET.ExtendMethods;
using Insus.NET.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace Insus.NET.Controllers
{
    public class FileController : ApiController
    {
        // GET: File
        FileEntity fe = new FileEntity();

        // GET: ApiFileDemo

        [HttpGet]
        public string Get(int id)
        {
            File f = new File();
            f.Afd_nbr = id;
            return fe.GetFileByPrimarykey(f).ToJson();
        }

        [HttpPost]
        public void Post(File f)
        {
            fe.Insert(f);
        }

        [HttpPut]
        public void Put(File f)
        {
            fe.Update(f);
        }

        [HttpDelete]
        public void Delete(File f)
        {
            fe.Delete(f);
        }

        [HttpDelete]
        public void Delete(int id)
        {
            File f = new File();
            f.Afd_nbr = id;
            fe.Delete(f);
        }
    }
}

 
其1过滤器SecurityAuthorizeAttribute.cs,稍后我们会在控制器中动用到它。

管理结果:
997755.com澳门葡京 54

Source Code

Source Code

收下你必要写调节器了,不,大家就像少写了1部分物件,如model和Entity:

 

 
Web
API实现,大家须要把它公布至IIS中去,怎么着公布,可以参见《创制与使用Web
API》……

 
Web
API实现,我们须要把它揭发至IIS中去,如何发布,能够参考《开创与使用Web
API》……

997755.com澳门葡京 55

Ok,接下去,大家开辟客户端的次第,尝试上Web API上传一些文本。

Ok,接下去,大家开拓客户端的主次,尝试上Web API上传一些文件。

 

在客户端的品类中,创造二个mode:
997755.com澳门葡京 56

在客户端的项目中,创制一个mode:
997755.com澳门葡京 57

Models写好,还差四个Entity,那个实体是与数据连接的物件:
997755.com澳门葡京 58

997755.com澳门葡京 59997755.com澳门葡京 60

997755.com澳门葡京 61997755.com澳门葡京 62

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Insus.NET.Models
{
    public class File
    {
        public int Afd_nbr { get; set; }

        public byte[] Picture { get; set; }

        public string PictureType { get; set; }

        public string FileExtension { get; set; }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Insus.NET.Models
{
    public class File
    {
        public int Afd_nbr { get; set; }

        public byte[] Picture { get; set; }

        public string PictureType { get; set; }

        public string FileExtension { get; set; }
    }
}

在ASP.NET
MVC中,落成登入验证的以身作则,最少要求多少个调控器,2个是给无名氏用户访问的,它富含普通的页面和一部分着力的操作。另2个调整器是通过验证通过之后手艺访问的页面。
997755.com澳门葡京 63

Source Code

Source Code

另二个调整器:
997755.com澳门葡京 64

 

 

 

ASP.NET MVC的调控器中,创设1个Action:
997755.com澳门葡京 65

ASP.NET MVC的调节器中,创立叁个Action:
997755.com澳门葡京 66

997755.com澳门葡京,最终是创设视图了:
997755.com澳门葡京 67

 

 

 

997755.com澳门葡京 68997755.com澳门葡京 69

997755.com澳门葡京 70997755.com澳门葡京 71

997755.com澳门葡京 72997755.com澳门葡京 73

 public ActionResult Upload()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Upload(IEnumerable<HttpPostedFileBase> files)
        {
            foreach (var file in files)
            {
                if (file.ContentLength > 0)
                {
                    Insus.NET.Models.File f = new Insus.NET.Models.File();
                    f.PictureType = file.ContentType;
                    string fn = Path.GetFileName(file.FileName);
                    f.FileExtension = fn.Substring(fn.LastIndexOf('.'));
                    using (Stream inputStream = file.InputStream)
                    {
                        MemoryStream memoryStream = inputStream as MemoryStream;
                        if (memoryStream == null)
                        {
                            memoryStream = new MemoryStream();
                            inputStream.CopyTo(memoryStream);
                        }
                        f.Picture = memoryStream.ToArray();
                    }
                    HttpClient client = new HttpClient();
                    string ff = f.ToJson();
                    HttpContent httpcontent = new StringContent(ff, System.Text.Encoding.UTF8, "application/json");
                    client.PostAsync("http://localhost:9001/api/file", httpcontent)
                        .ContinueWith((postTask) =>
                        {
                            postTask.Result.EnsureSuccessStatusCode();
                        });
                }
            }
            return RedirectToAction("Upload");
        }
 public ActionResult Upload()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Upload(IEnumerable<HttpPostedFileBase> files)
        {
            foreach (var file in files)
            {
                if (file.ContentLength > 0)
                {
                    Insus.NET.Models.File f = new Insus.NET.Models.File();
                    f.PictureType = file.ContentType;
                    string fn = Path.GetFileName(file.FileName);
                    f.FileExtension = fn.Substring(fn.LastIndexOf('.'));
                    using (Stream inputStream = file.InputStream)
                    {
                        MemoryStream memoryStream = inputStream as MemoryStream;
                        if (memoryStream == null)
                        {
                            memoryStream = new MemoryStream();
                            inputStream.CopyTo(memoryStream);
                        }
                        f.Picture = memoryStream.ToArray();
                    }
                    HttpClient client = new HttpClient();
                    string ff = f.ToJson();
                    HttpContent httpcontent = new StringContent(ff, System.Text.Encoding.UTF8, "application/json");
                    client.PostAsync("http://localhost:9001/api/file", httpcontent)
                        .ContinueWith((postTask) =>
                        {
                            postTask.Result.EnsureSuccessStatusCode();
                        });
                }
            }
            return RedirectToAction("Upload");
        }
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>

    <style type="text/css">
        #logincontact label {
            display: inline-block;
            width: 100px;
            text-align: right;
        }

        #logincontact_submit {
            padding-left: 100px;
        }

        #logincontact div {
            margin-top: 1em;
        }

        .error {
            display: none;
            margin-left: 10px;
        }

        .error_show {
            color: red;
            margin-left: 10px;
        }

        input.invalid {
            border: 2px solid red;
        }

        input.valid {
            border: 2px solid green;
        }
    </style>

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

    <script type="text/javascript">
        ////<![CDATA[
        $(document).ready(function () {
            $('#logincontact_Account').on('input', function () {
                var input = $(this);
                var is_Account = input.val();
                if (is_Account) {
                    input.removeClass("invalid").addClass("valid");
                }
                else {
                    input.removeClass("valid").addClass("invalid");
                }
            });


            $('#logincontact_Password').on('input', function () {
                var input = $(this);
                var is_Password = input.val();
                if (is_Password) {
                    input.removeClass("invalid").addClass("valid");
                }
                else {
                    input.removeClass("valid").addClass("invalid");
                }
            });


            $('#ButtonSignIn').click(function (event) {
                var form_data = $("#logincontact").serializeArray();
                var error_free = true;
                for (var input in form_data) {
                    var element = $("#logincontact_" + form_data[input]['name']);
                    var valid = element.hasClass("valid");
                    var error_element = $("span", element.parent());

                    if (!valid) {
                        error_element.removeClass("error").addClass("error_show");
                        error_free = false;
                    }
                    else {
                        error_element.removeClass("error_show").addClass("error");
                    }
                }

                if (!error_free) {
                    event.preventDefault();
                }
                else {
                    var obj = {};
                    obj.Account = $('#logincontact_Account').val(),
                    obj.Password = $('#logincontact_Password').val()

                    $.ajax({
                        type: 'POST',
                        url: '/Home/LoginVerify',
                        dataType: 'json',
                        data: JSON.stringify(obj),
                        contentType: 'application/json; charset=utf-8',
                        success: function (data, textStatus) {
                            alert("登录成功。");
                            window.location.href = "/User/Index";
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert(errorThrown);
                        },
                    });
                }
            });
        });
        //]]>
    </script>
</head>
<body>
    <form id="logincontact" method="post" action="">
        <div>
            <label for="logincontact_Account">Account:</label>
            <input type="text" id="logincontact_Account" name="Account" />
            This account field is required.
        </div>
        <div>
            <label for="logincontact_Password">Password:</label>
            <input type="password" id="logincontact_Password" name="Password" />
            This password field is required.
        </div>
        <div id="logincontact_submit">
            <input id="ButtonSignIn" type="button" value="Sign In" />
        </div>
    </form>
</body>
</html>

Source Code

Source Code

Source Code

 

 

 

在视图中,能够如此做:
997755.com澳门葡京 74

在视图中,能够这么做:
997755.com澳门葡京 75

再有叁个:
997755.com澳门葡京 76

 

 

 

程序运营:
997755.com澳门葡京 77

程序运维:
997755.com澳门葡京 78

997755.com澳门葡京 79997755.com澳门葡京 80

 

 

@{
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script src="~/Scripts/jquery-2.2.1.js"></script>

    <script type="text/javascript">
        ////<![CDATA[
        $(document).ready(function () {

            $('#ButtonSignOut').click(function (event) {
                $.ajax({
                    type: 'POST',
                    url: '/Home/SignOut',                                  
                    contentType: 'application/json; charset=utf-8',
                    success: function (data, textStatus) {
                        alert("已经安全退出网站。");
                        window.location.href = "/Home/Index";
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert(errorThrown);
                    },
                });
            });
        });
        //]]>
    </script>
</head>
<body>
    <div>
        Hi @ViewBag.UserName
        <br />
        <input id="ButtonSignOut" type="button" value="Sign Out" />
    </div>
</body>
</html>

 图片上传成功现在,今后大家须求把图纸体现出来。
出于存款和储蓄的是二进制的数据流,突显图片时,要求管理一下,供给写三个自定义的Result,如:PictureResult,它要求继续ContentResult:
997755.com澳门葡京 81

 图片上传成功未来,未来大家须要把图片展现出来。
由于存款和储蓄的是二进制的数据流,展现图片时,需求管理一下,须求写三个自定义的Result,如:PictureResult,它供给持续ContentResult:
997755.com澳门葡京 82

Source Code

997755.com澳门葡京 83997755.com澳门葡京 84

997755.com澳门葡京 85997755.com澳门葡京 86

利落了,来三个实时演示吧:
997755.com澳门葡京 87

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace Insus.NET.Results
{
    public class PictureResult : ContentResult
    {
        public byte[] _Picture { get; set; }
        public string _PictureType { get; set; }

        public PictureResult(byte[] sourceStream, String contentType)
        {
            _Picture = sourceStream;
            _PictureType = contentType;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            var response = context.HttpContext.Response;
            response.Clear();
            response.Cache.SetCacheability(HttpCacheability.NoCache);
            response.ContentType = ContentType;

            if (_Picture != null)
            {
                var stream = new MemoryStream(_Picture);
                stream.WriteTo(response.OutputStream);
                stream.Dispose();
            }
        }
    }
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace Insus.NET.Results
{
    public class PictureResult : ContentResult
    {
        public byte[] _Picture { get; set; }
        public string _PictureType { get; set; }

        public PictureResult(byte[] sourceStream, String contentType)
        {
            _Picture = sourceStream;
            _PictureType = contentType;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            var response = context.HttpContext.Response;
            response.Clear();
            response.Cache.SetCacheability(HttpCacheability.NoCache);
            response.ContentType = ContentType;

            if (_Picture != null)
            {
                var stream = new MemoryStream(_Picture);
                stream.WriteTo(response.OutputStream);
                stream.Dispose();
            }
        }
    }
}

 

Source Code

Source Code

接下去,大家在调整器创设视图的Action:
997755.com澳门葡京 88

接下去,大家在调节器创立视图的Action:
997755.com澳门葡京 89

 

 

997755.com澳门葡京 90997755.com澳门葡京 91

997755.com澳门葡京 92997755.com澳门葡京 93

 public ActionResult ShowPhoto()
        {
            return View();
        }

        public ActionResult ShowPicture(int id)
        {
            var files = ApiUtility.Get<Insus.NET.Models.File>("http://localhost:9001/api/file/" + id);
            var model = files.FirstOrDefault();

            PictureResult pictureResult = new PictureResult(model.Picture, model.PictureType);
            return pictureResult;
        }
 public ActionResult ShowPhoto()
        {
            return View();
        }

        public ActionResult ShowPicture(int id)
        {
            var files = ApiUtility.Get<Insus.NET.Models.File>("http://localhost:9001/api/file/" + id);
            var model = files.FirstOrDefault();

            PictureResult pictureResult = new PictureResult(model.Picture, model.PictureType);
            return pictureResult;
        }

Source Code

Source Code

 
客户端程序运转,可以看来图片体现的效用:
997755.com澳门葡京 94

 
客户端程序运营,能够阅览图片呈现的职能:
997755.com澳门葡京 95

在Web
API的接口还有创新,删除的接口,看官们能够继续达成。方法在Insus.NET博客上也有一般或许相关的成效……

在Web
API的接口还有立异,删除的接口,看官们能够接二连三完毕。方法在Insus.NET博客上也有一般大概相关的机能……

 

 

相关文章

发表评论

电子邮件地址不会被公开。 必填项已用*标注

*
*
Website