计算结余数,API与文件操作

有二个网民问及,在SQL中,计算每一笔的剩余数。他提供的截图申明:
图片 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有在数据库完结过对某一字段展开加密码与解密《应用EncryptByPassPapakōlea沙滩se和DecryptByPass莫纳克亚沙滩se对MS SQLServer某一字段时行加密和解密》[

 

无论怎么着,先在数据库创立一张表,用来囤积上传的文本。本实例中是把文件存款和储蓄过数据库的。

不管如何,先在数据库创设一张表,用来积存上传的公文。本实例中是把文件存款和储蓄过数据库的。

]( MVC完毕自定义验证Authorize Attribute。

图片 2

图片 3

图片 4

达成以前,Insus.NET对usp_Users_VeryLoginVerify修改一下,改为更加好明白与运用:
图片 5

 

图片 6图片 7

图片 8图片 9

 

实现这么些职能,关键是赢得前一笔记录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

图片 10图片 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

成立贰个不时表存储原数:
图片 12

写到这里,开掘少了多少个仓库储存进度,正是赢得某一张图纸的:
图片 13

写到这里,开采少了二个仓库储存进度,便是获得某一张图纸的:
图片 14

Source Code

图片 15图片 16

图片 17图片 18

图片 19图片 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来储存登入以及表明信息,写多个库克ie体系:
图片 21

 

 
接下去,大家得以设计Web API接口,待完毕了,宣布至网络,其它顾客端即可操作了。

 
接下去,大家能够安顿Web API接口,待完结了,公布至英特网,另外客商端就足以操作了。

计算结余数,API与文件操作。 

我们开端拍卖,创立别的叁个有的时候表,原始表相似,可是供给增添2个字段,id和eqty。个中id是理所必然增进的identity(1,1)。

听闻数据库表,能够在API项目中,创制Model:
图片 22

基于数量库表,能够在API项目中,创立Model:
图片 23

图片 24图片 25

还亟需把原本数据搬到此新建的偶然表中:
图片 26

图片 27图片 28

图片 29图片 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

图片 31图片 32

Source Code

Source Code

 
实质上下面这一个CookeBase.cs是一个能积攒多目的的集结类。在真正的前后相继中,你想囤积什么消息,能够写叁个如下边包车型客车类来操作:
图片 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写八个实体,这一个指标只是让程序与数据库举行互动。获取与储存等操作:
图片 34

写好model之后,还须要为API写一个实体,这些目的只是让程序与数据库实行互动。获取与存款和储蓄等操作:
图片 35

 

Source Code

图片 36图片 37

图片 38图片 39

图片 40图片 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写了四个存储进度,方法如下:
图片 42

Source Code

Source Code

Source Code

 

 

 

接下去,我们必要创设三个证实过滤器:
图片 43

图片 44图片 45

上面包车型客车操纵器FileController,正是为客户端访谈的接口,那么些类型,它是持续了ApiController。
图片 46

上边包车型大巴调节器FileController,正是为客商端访问的接口,这些项目,它是三番两次了ApiController。
图片 47

图片 48图片 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

图片 50图片 51

图片 52图片 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);
        }
    }
}

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

管理结果:
图片 54

Source Code

Source Code

接收你须要写调整器了,不,大家就好像少写了一部分物件,如model和Entity:

 

 
Web API达成,大家必要把它揭穿至IIS中去,怎么着宣布,能够参照《创制与使用Web API》......

 
Web API实现,我们供给把它揭发至IIS中去,怎么样发布,能够参照《创办与应用Web API》......

图片 55

Ok,接下去,我们开拓顾客端的顺序,尝试上Web API上传一些文书。

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

 

在顾客端的花色中,创立贰个mode:
图片 56

在客商端的类别中,创制一个mode:
图片 57

Models写好,还差一个Entity,这一个实体是与数据连接的物件:
图片 58

图片 59图片 60

图片 61图片 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中,实现登入验证的自己要作为范例遵守规则,最少需求多个调控器,三个是给无名氏客商访谈的,它富含普通的页面和部分宗旨的操作。另叁个调控器是经过验证通过之后技术访谈的页面。
图片 63

Source Code

Source Code

另八个调节器:
图片 64

 

 

 

ASP.NET MVC的调节器中,成立2个Action:
图片 65

ASP.NET MVC的调整器中,创制2个Action:
图片 66

终极是创办视图了:
图片 67

 

 

 

图片 68图片 69

图片 70图片 71

图片 72图片 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

 

 

 

在视图中,可以那样做:
图片 74

在视图中,能够如此做:
图片 75

再有多个:
图片 76

 

 

 

程序运营:
图片 77

程序运转:
图片 78

图片 79图片 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:
图片 81

 图片上传成功以往,以后大家须求把图纸显示出来。
出于存款和储蓄的是二进制的数据流,展现图片时,要求管理一下,须要写贰个自定义的Result,如:PictureResult,它需求延续ContentResult:
图片 82

Source Code

图片 83图片 84

图片 85图片 86

终止了,来二个实时演示吧:
图片 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:
图片 88

接下去,大家在调节器创制视图的Action:
图片 89

 

 

图片 90图片 91

图片 92图片 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

 
客商端程序运营,能够看出图片突显的意义:
图片 94

 
顾客端程序运营,可以看看图片显示的功用:
图片 95

在Web API的接口还会有立异,删除的接口,看官们能够继续达成。方法在Insus.NET博客上也会有一般恐怕相关的成效......

在Web API的接口还应该有创新,删除的接口,看官们能够接二连三完结。方法在Insus.NET博客上也可能有一般恐怕相关的效应......

 

 

本文由星彩网app下载发布于星彩彩票app下载,转载请注明出处:计算结余数,API与文件操作

TAG标签:
Ctrl+D 将本页面保存为书签,全面了解最新资讯,方便快捷。