您的位置:首页 > 其它

钉钉开发系列(六)WebApi

2016-05-23 18:23 267 查看
之前常使用的方式是html+ajax+ashx(一般处理程序),这样的方案也是不错的,但比起WebApi来,还是不够方便。WebApi的关键就是路由配置。为此我们先建一个WebApiConfig.cs的配置文件,代码如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Http;

namespace DingDingWeb
{
public class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
//注册路由映射
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",//action表示按方法路由
defaults: new { id = RouteParameter.Optional }
);
}
}
}
再添加一个全局的Global.asax,代码如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Security;
using System.Web.SessionState;

namespace DingDingWeb
{
public class Global : System.Web.HttpApplication
{

protected void Application_Start(object sender, EventArgs e)
{
WebApiConfig.Register(GlobalConfiguration.Configuration);
}

protected void Session_Start(object sender, EventArgs e)
{

}

protected void Application_BeginRequest(object sender, EventArgs e)
{

}

protected void Application_AuthenticateRequest(object sender, EventArgs e)
{

}

protected void Application_Error(object sender, EventArgs e)
{

}

protected void Session_End(object sender, EventArgs e)
{

}

protected void Application_End(object sender, EventArgs e)
{

}
}
}
记得在项目中加入System.Net.Http、System.Web.Http、System.Web.Http.WebHost的引用,同时使用nuget来安装Newtonsoft.Json的库(自己引用很可能会出现兼容问题而导到运转起来报Newtonsoft.Json版本的错误)。

再建一个controller的文件夹,里面增加一个相关的类,类名的后面一定要是Controller。比如我们定义一个授权类AuthController。

public class AuthController : ApiController
{
#region GetSignPackage Function
/// <summary>
/// 获取签名包
/// </summary>
public SignPackage GetSignPackage(String url)
{
//对于首页的URL,由于可以直接使用域名跳转来进入(比如http://www.king-ecs.com),所以这时取的URL其实是域名,
//而不是当前页的URL(http://www.king-ecs.com/index.html),这时产生的签名包是针对域名的(即http://www.king-ecs.com)。
//这样一来就有会造成服务端计算的签名和钉钉计算出的签名不致,从而导致验证失败。
//所以首页URL跳转需要签名名时,需要将URL传入以计算签名包。
//string url = HttpContext.Current.Request.Url.AbsoluteUri;
var signPackage = SdkTool.FetchSignPackage(url);
return signPackage;
}
#endregion
}
这个API就是global.js中调用的方法。方法名记得使用Get开头,否则无法以GET的请求方式获取。获取增加[HttpGet]的契约。比如下面的方法

#region Register Function
/// <summary>
/// 登记群
/// </summary>
/// <param name="chatId"></param>
[HttpGet]//方法名以Get开头则不需要加HttpGet的标识,否则无法以Get方式发起请求
public RequestResult Register(String chatId)
{
//记录到数据库
}
有了路由请求后,代码就会比较方便,而且返回的结果都是以json的方式返回的,所以JS端以$.getJSON来获取就变的相当方便。据此我们可以调用biz.chat.chooseConversationByCorpId来获取企业群的chatId,然后记录到数据库中。这样在服务端还没有可以获取chatId接口的情况下,也可以曲线达到目的,虽然麻烦了一点。

以上WepApi的方式,也适用于其他的Web开发。

转载请注明出处。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: