当前位置: 移动技术网 > IT编程>开发语言>.net > C#净化版WebApi框架

C#净化版WebApi框架

2019年03月27日  | 移动技术网IT编程  | 我要评论

前言

我们都知道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文件,编写如下代码:

protected void application_start()
{ 
    globalconfiguration.configure(webapiconfig.register);  
    globalconfiguration.configuration.formatters.xmlformatter.supportedmediatypes.clear();//删除xml格式 回應
}

可以看到,我们已通过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;
        } 
    }
} public class baseapicontroller : apicontroller { public string options() { return null; } }

然后我们运行网站,进行webapi访问。

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

----------------------------------------------------------------------------------------------------

到此c#净化版webapi框架就介绍完了。

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

github地址:https://github.com/kiba518/webapi

----------------------------------------------------------------------------------------------------

注:此文章为原创,欢迎转载,请在文章页面明显位置给出此文链接!
若您觉得这篇文章还不错,请点击下方的推荐】,非常感谢!

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网