C#净化版WebApi框架的实现

作者:kiba518 时间:2021-10-31 03:59:09 

前言

我们都知道WebApi是依赖于Asp.Net MVC的 ,所以,想创建WebApi,就需要先创建一个Asp.Net MVC项目。

但用Visual Studio创建的MVC项目通常会带很多功能,而这些功能,很多是我们并不想用的,或者我们想用其他开源控件代替它。

而这样杂乱的起始项目,对于我们这种有精神洁癖的开发者而言,简直是折磨。

所以,让我们编写一个简洁版本的WebApi来净化世界吧。

净化版WebApi预览

首先,我们先看下净化版WebApi的结构。

C#净化版WebApi框架的实现

如上图所示,代码结构很简单,除开配置文件,整个Web项目只有2个文件;而需要被调用的WebApi都被封装到了WebApi程序集中了。

接下来我们一起看下编写这个净化版WebApi的过程吧。

净化版WebApi编写

WebApiConfig

首先,引入必要的Dll,如下图所示。

C#净化版WebApi框架的实现

然后,我们编写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访问。

C#净化版WebApi框架的实现

如上图所示,我们的WebApi访问成功。

到此C#净化版WebApi框架就介绍完了。

框架代码已经传到Github上了,欢迎大家下载。

Github地址:https://github.com/kiba518/WebApi

来源:http://www.cnblogs.com/kiba/p/10598626.html

标签:C#,WebApi框架
0
投稿

猜你喜欢

  • C#实现自定义单选和复选按钮样式

    2022-07-22 04:01:41
  • Java实现布隆过滤器的方法步骤

    2023-02-15 20:31:47
  • Android自定义View实现拼图小游戏

    2023-07-13 13:53:39
  • spring中的注解事务演示和添加步骤详情

    2023-03-03 08:32:48
  • Android自定义控制条效果

    2023-01-23 23:59:12
  • 解决idea中yml文件图标问题及自动提示失效的情况

    2021-06-08 14:59:42
  • Java数据结构之链表、栈、队列、树的实现方法示例

    2021-10-07 10:40:29
  • Java I/O 操作及优化详细介绍

    2022-07-30 14:46:42
  • 使用JVM常用GC日志打印参数

    2021-09-06 17:36:41
  • 编写android拨打电话apk应用实例代码

    2021-08-25 11:09:12
  • SpringBoot中如何对actuator进行关闭

    2022-11-30 01:56:37
  • Spring Boot Logback配置日志过程解析

    2022-12-09 18:08:06
  • SpringMVC如何获取表单数据(radio和checkbox)

    2022-02-19 05:27:01
  • Java简易登录注册小程序

    2023-01-23 09:16:13
  • 使用递归实现数组求和示例分享

    2023-04-24 02:17:40
  • Mybatis打印替换占位符后的完整Sql教程

    2023-11-08 22:56:13
  • SpringCache框架加载/拦截原理详解

    2023-04-11 10:31:46
  • 微信公众号开发之回复图文消息java代码

    2022-11-24 00:56:19
  • Minio与SpringBoot使用okhttp3问题解决

    2021-06-25 19:17:08
  • 用Newtonsoft将json串转为对象的方法(详解)

    2022-12-31 23:32:21
  • asp之家 软件编程 m.aspxhome.com