本章内容和大家分享的是Asp.NetCore组件写法,在netcore中很多东西都以提供组件的方式来使用,比如MVC架构,Session,Cache,数据库引用等; 这里我也通过调用验证码接口来自定义个组件以此说明如何使用,以及使用时需要注意的场景;
Middleware之hello world
对于netcore来说,通常会在UseStartup<Startup>对应的Startup类中引用组件,这个Startup可以换成自己自定义的其实类,不过需要在UseStartup的时候指向她;这里还是以Startup类为例,通过vs自动生成的文件,在这个类中我们能看到Configure方法体里面包含了:app.UseMvc(),app.UseStaticFiles(),app.xxx()等一些列自带的组件,下面来看下自定义个hello world中组件实例,首先使用静态扩展方法扩展IApplicationBuilder:
public static class MiddlewareExtends
{
/// <summary>
/// 测试用例中间件
/// </summary>
/// <param name="builder"></param>
/// <returns></returns>
public static IApplicationBuilder UseTest(this IApplicationBuilder builder)
{
return builder.UseMiddleware<TestMiddleware>();
} }
使用 builder.UseMiddleware<TestMiddleware>() 来添加自定义组件,组件实现代码如下:
public class TestMiddleware
{
private RequestDelegate _requestDelegate;
public TestMiddleware(RequestDelegate requestDelegate)
{
_requestDelegate = requestDelegate;
} public Task Invoke(HttpContext context)
{ context.Items["TestMiddleware"] = "hello world,我是TestMiddleware。"; return _requestDelegate(context);
}
}
以上是最基础的组件格式;注:
1. 组件必须要有 public Task Invoke(HttpContext context) ,HttpContext是咋们http上下文,Invoke()委托方法,每次程序被访问时就会进入Invoke;
2. 要有 public delegate Task RequestDelegate(HttpContext context); 委托方法,来响应http请求;
到这里咋们hello world就完成了,为了测试方法,我们直接在action中写入如下代码:
public IActionResult About()
{ ViewData["Message"] = HttpContext.Items["TestMiddleware"];
return View();
}
运行结果:
组件异步写法
public class TestMiddleware
{
private RequestDelegate _requestDelegate;
public TestMiddleware(RequestDelegate requestDelegate)
{
_requestDelegate = requestDelegate;
} public async Task Invoke(HttpContext context)
{ context.Items["TestMiddleware"] = "hello world,我是asyncTestMiddleware。"; await _requestDelegate(context);
}
}
仅仅需要async 和 await 组合修饰就行了;
.netcore自定义验证码组件
/// <summary>
/// 文字验证码
/// </summary>
public class WenZiCodeMiddleware
{
private RequestDelegate _requestDelegate;
public WenZiCodeMiddleware(RequestDelegate requestDelegate)
{
_requestDelegate = requestDelegate;
} public async Task Invoke(HttpContext context)
{ var url = "http://localhost:1001/shenniuapi/WenZiValidateCode";
using (HttpClient client = new HttpClient())
{
client.Timeout = TimeSpan.FromSeconds(); var str = "{\"UserName\": \"神牛步行3\",\"UserPwd\": \"4297f44b13955235245b2497399d7a93\",\"Token\": \"008我是测试\"}";
var content = new StringContent(str, Encoding.UTF8, "application/x-www-form-urlencoded");
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var result01 = client.PostAsync(url, content).Result;
var stream = await result01.Content.ReadAsStreamAsync();
using (var reader = new StreamReader(stream))
{
var result02 = await reader.ReadToEndAsync();
context.Items["codedata"] = result02;
}
} await _requestDelegate(context);
}
}
我们同样需要再静态扩展方法里面添加如下代码,来加入组件:
/// <summary>
/// 文字验证码中间件
/// </summary>
/// <param name="builder"></param>
/// <returns></returns>
public static IApplicationBuilder UseWenZiValidateCode(this IApplicationBuilder builder)
{
return builder.UseMiddleware<WenZiCodeMiddleware>();
}
在Configure方法中,引用组件: app.UseWenZiValidateCode(); ;Action中,使用组件:
public FileResult GetCode()
{
var data = HttpContext.Items["codedata"].ToString();
var code = JsonConvert.DeserializeObject<MoValidateCodeResponse>(data);
return File(code.CodeStream, "image/jpeg");
}
View试图中代码:
GetCode:<img src="/home/GetCode" data-src="/home/GetCode" />
效果展示:
这里需要考虑场景是,我们上面提及到的Invoke方法是任意请求都会进入,那验证码这种功能做成组件是否不是很合理,因为验证码也只有在登陆界面或验证的界面需要用到而已,如我们上面写的验证码组件,每次都会被程序执行这显然不合理,因此个人认为如果你需要自定义组件,那么需要考量:是否每次请求都需要进入您的组件服务,如果不需要的话,那其实没必要弄一个组件,当然感觉很高大上;因此这里我不得不使用静态扩展方法(当然还有其他方式)来重写获取验证码的方法;
静态扩展方法重写验证码组件
由于上面我们在添加组件时有一个静态类了,那么我们直接在上面补充扩展方法:
/// <summary>
/// 文字验证码
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public static async Task<MoValidateCodeResponse> WenZiCode(this HttpContext context)
{
var code = default(MoValidateCodeResponse);
try
{
var url = "http://localhost:1001/shenniuapi/WenZiValidateCode";
using (HttpClient client = new HttpClient())
{
client.Timeout = TimeSpan.FromSeconds(); var str = "{\"UserName\": \"神牛步行3\",\"UserPwd\": \"4297f44b13955235245b2497399d7a93\",\"Token\": \"008我是测试\"}";
var content = new StringContent(str, Encoding.UTF8, "application/x-www-form-urlencoded");
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var result01 = client.PostAsync(url, content).Result;
var stream = await result01.Content.ReadAsStreamAsync();
using (var reader = new StreamReader(stream))
{
var result02 = await reader.ReadToEndAsync();
code = await JsonConvert.DeserializeObjectAsync<MoValidateCodeResponse>(result02);
}
}
}
catch (Exception ex)
{
}
return code;
}
对应的验证码实体类:
/// <summary>
/// 神牛接口返回基类
/// </summary>
public class MoShenNiuBaseResponse
{
/// <summary>
/// 返回状态: 0:失败 1:成功
/// </summary>
public int Status { get; set; } /// <summary>
/// 错误信息
/// </summary>
public string Msg { get; set; }
} /// <summary>
/// 验证码返回类
/// </summary>
public class MoValidateCodeResponse : MoShenNiuBaseResponse
{ public MoValidateCodeResponse()
{
this.ImgCode = new List<MoImgCode>();
} /// <summary>
/// 验证码类型
/// </summary>
public string Code { get; set; } /// <summary>
/// 验证码图片流
/// </summary>
public byte[] CodeStream { get; set; } /// <summary>
/// 图片验证坐标
/// </summary>
public List<MoImgCode> ImgCode;
} /// <summary>
/// 图片验证码坐标
/// </summary>
public class MoImgCode
{
public string Index { get; set; } public string IndexType { get; set; } public string ImgUrl { get; set; } public Point Point_A { get; set; } public Point Point_B { get; set; } public bool IsChoice { get; set; }
} public class Point
{
public int X { get; set; }
public int Y { get; set; }
}
这个时候同样来到Action中:
public async Task<FileResult> GetCodeAsync()
{
var code = await HttpContext.WenZiCode(); return File(code.CodeStream, "image/jpeg");
}
修改view试图代码,增加点击验证码图片重新获取新的验证码:
<style type="text/css">
img{cursor:pointer}
</style>
<h3>@ViewData["Message"]</h3>
<h3>@ViewData["codedata"]</h3>
GetCode:<img src="/home/GetCode" data-src="/home/GetCode" />
GetCodeAsync:<img src="/home/GetCodeAsync" data-src="/home/GetCodeAsync" /> <script src="~/lib/jquery/dist/jquery.js"></script>
<script>
$(function () {
$("img").on("click", function () {
var img = this;
var nowTime = new Date().getTime();
var src = $(img).attr("data-src") + "?t=" + nowTime;
$(img).attr("src", src);
});
})
</script>
效果图:
以上就是本篇的所有内容,旨在分享怎么写一个组件和什么时候用组件合适,谢谢大家支持和点赞。