C#净化版WebApi框架的实现
作者:kiba518 时间:2021-10-31 03:59:09
前言
我们都知道WebApi是依赖于Asp.Net MVC的 ,所以,想创建WebApi,就需要先创建一个Asp.Net MVC项目。
但用Visual Studio创建的MVC项目通常会带很多功能,而这些功能,很多是我们并不想用的,或者我们想用其他开源控件代替它。
而这样杂乱的起始项目,对于我们这种有精神洁癖的开发者而言,简直是折磨。
所以,让我们编写一个简洁版本的WebApi来净化世界吧。
净化版WebApi预览
首先,我们先看下净化版WebApi的结构。
如上图所示,代码结构很简单,除开配置文件,整个Web项目只有2个文件;而需要被调用的WebApi都被封装到了WebApi程序集中了。
接下来我们一起看下编写这个净化版WebApi的过程吧。
净化版WebApi编写
WebApiConfig
首先,引入必要的Dll,如下图所示。
然后,我们编写Web项目的写WebApiConfig;代码如下:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Filters.Add(new WebApiAttribute());
// 解决json序列化时的循环引用问题
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
// 对 JSON 数据使用混合大小写。跟属性名同样的大小.输出
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new DefaultContractResolver();
// Web API 路由
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "webapi/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
可以看到WebApiConfig是个静态类中,我们在其中创建了静态注册方法Register,在方法内,我们主要在做一件事,那就是为HttpConfiguration对象做配置。
而在配置中,我们将WepApi的路由配置成了webapi/{controller}/{id},也就是说,我们的WebApi未来的访问地址将为【http://localhost:5180/webapi/Login】这样的模式。
在WebApiConfig类中,我们还用到了这样一个类WebApiAttribute,我们在为HttpConfiguration对象的Filters属性,添加了这个类的对象。
通过Filters属性这个字样,我们可以得出,这个类主要应用应该是过滤。
下面我们看一下这个类的代码:
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class WebApiAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
//API执行前触发
if (true)//当前设置,所有API都可以被调用
{
base.OnActionExecuting(actionContext);
}
else
{
throw new Exception("Error");
}
}
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
//API执行后触发 若发生例外则不在这边处理
if (actionExecutedContext.Exception != null)
return;
base.OnActionExecuted(actionExecutedContext);
}
}
通过阅读代码,我们应该可以发现,这是一个AOP的过滤器。
在执行真正WebApi之前,会先进入这里进行过滤,过滤通过的API,才会调用base.OnActionExecuting(actionContext)方法进行调用和执行。
结束调用同理,结束调用前,会在该类中进行拦截和过滤处理。
配置文件
WebApiConfig编写结束了,现在,我们需要将这个静态类注册到项目中。
打开Global.asax文件,编写如下代码:
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class WebApiAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
//API执行前触发
if (true)//当前设置,所有API都可以被调用
{
base.OnActionExecuting(actionContext);
}
else
{
throw new Exception("Error");
}
}
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
//API执行后触发 若发生例外则不在这边处理
if (actionExecutedContext.Exception != null)
return;
base.OnActionExecuted(actionExecutedContext);
}
}
可以看到,我们已通过Configure方法,将我们编写好的WebApiConfig添加到了全局配置中了。
因为网站访问都存在跨域问题,所以我们再向Global.asax中添加如下代码处理:
protected void Application_BeginRequest(object sender, System.EventArgs e)
{
var req = System.Web.HttpContext.Current.Request;
if (req.HttpMethod == "OPTIONS")//过滤options请求,用于js跨域
{
Response.StatusCode = 200;
Response.SubStatusCode = 200;
Response.End();
}
}
到此Web项目的编写就完成了,下面我们在WebApi程序集中,编写个简单的WebApi,代码如下:
public class LoginController : BaseApiController
{
public BaseResult Get()
{
try
{
return new BaseResult() { IsSuccess=true };
}
catch (Exception ex)
{
throw ex;
}
}<br>}
public class BaseApiController : ApiController
{
public string Options()
{
return null;
}
}
然后我们运行网站,进行WebApi访问。
如上图所示,我们的WebApi访问成功。
到此C#净化版WebApi框架就介绍完了。
框架代码已经传到Github上了,欢迎大家下载。
Github地址:https://github.com/kiba518/WebApi
来源:http://www.cnblogs.com/kiba/p/10598626.html
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
C#实现自定义单选和复选按钮样式
![](https://img.aspxhome.com/file/2023/2/87032_0s.png)
Java实现布隆过滤器的方法步骤
![](https://img.aspxhome.com/file/2023/4/61264_0s.jpg)
Android自定义View实现拼图小游戏
![](https://img.aspxhome.com/file/2023/3/95963_0s.gif)
spring中的注解事务演示和添加步骤详情
![](https://img.aspxhome.com/file/2023/3/77983_0s.png)
Android自定义控制条效果
![](https://img.aspxhome.com/file/2023/1/106051_0s.jpg)
解决idea中yml文件图标问题及自动提示失效的情况
![](https://img.aspxhome.com/file/2023/5/81915_0s.jpg)
Java数据结构之链表、栈、队列、树的实现方法示例
Java I/O 操作及优化详细介绍
![](https://img.aspxhome.com/file/2023/2/75752_0s.jpg)
使用JVM常用GC日志打印参数
![](https://img.aspxhome.com/file/2023/2/65752_0s.png)
编写android拨打电话apk应用实例代码
SpringBoot中如何对actuator进行关闭
![](https://img.aspxhome.com/file/2023/9/62349_0s.png)
Spring Boot Logback配置日志过程解析
SpringMVC如何获取表单数据(radio和checkbox)
![](https://img.aspxhome.com/file/2023/5/83155_0s.png)
Java简易登录注册小程序
使用递归实现数组求和示例分享
Mybatis打印替换占位符后的完整Sql教程
![](https://img.aspxhome.com/file/2023/5/97785_0s.jpg)
SpringCache框架加载/拦截原理详解
微信公众号开发之回复图文消息java代码
![](https://img.aspxhome.com/file/2023/1/86701_0s.jpg)
Minio与SpringBoot使用okhttp3问题解决
![](https://img.aspxhome.com/file/2023/1/83501_0s.jpg)