c#中WebApi开发遇到的坑

时间:2022-10-20 20:12:26

一、如何新建一个webApi项目

打开VS→找到解决方案→新建项目→类库或web应用程序→选择空的WebApi项目→在Global.asax文件的Application_Start方法中注册WebApi的相关配置→完成

二、如何对外提供api接口

在webApi项目的Controllers文件夹下新增一个类继承ApiController,在该类中就可以完成对外接口(GET、POST、PUT、DELETE等),需要注意的是如果提供的方法需要参数,则参数的类型不能按它实际的类型声明和传递,如Name不能直接声明为string类型,否则调用该接口时会报404错误,找不到该访问地址。声明的方式有很多种:

(1)创建一个类,该类只包含该方法所需的参数。

(2)引用FormDataCollection类来声明和接收参数。

这是常用的声明方式,推荐方法(2)。下面用例子的形式说明错误写法和正确写法

         #region 参数声明示例·错误写法
[Route("Example")]
[HttpPost]
public object Example(string name)
{
var response = new ResponseModel
{
StatusCode = ,
Message = "接收数据成功!",
Data = name
};
return Json(response);
}
#endregion
         #region 参数声明示例·正确写法
[Route("Example")]
[HttpPost]
public object Example(FormDataCollection collection)
{
var name = collection.Get("name");
var response = new ResponseModel
{
StatusCode = ,
Message = "接收数据成功!",
Data = name
};
return Json(response);
}
#endregion
         #region 参数声明示例·正确写法
[Route("Example")]
[HttpPost]
public object Example(DataInfo data)
{
var response = new ResponseModel
{
StatusCode = ,
Message = "接收数据成功!",
Data = data.Name
};
return Json(response);
}
#endregion public class DataInfo
{
public string Name { get; set; }
}

三、自定义票据验证筛选器

(1)创建类 AuthorFilter 继承 AuthorizeAttribute

 using System;
using System.Configuration;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Security;
using Xryang.Core.Config; namespace Xryang.Api.Author
{
public class AuthorFilter : AuthorizeAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
#region 验证token → 请求数据
var content = actionContext.Request.Properties["MS_HttpContext"] as HttpContextBase;
var token = content.Request.Headers["Secret"];
if (!string.IsNullOrEmpty(token))
{
//验证token
if (ValidateTicket(token))
{
base.IsAuthorized(actionContext);
}
else
{
HandleUnauthorizedRequest(actionContext);
}
return;
}
#endregion #region 请求token
var appId = content.Request.Headers["AppId"];
if (!string.IsNullOrEmpty(appId))
{
//验证AppId
if (IsAllowAppId(appId))
{
base.IsAuthorized(actionContext);
}
else
{
HandleUnauthorizedRequest(actionContext);
}
return;
}
#endregion #region 非法请求
HandleUnauthorizedRequest(actionContext);
#endregion
} #region 验证Token
//校验票据(数据库数据匹配)
private bool ValidateTicket(string token)
{
bool flag = false;
try
{
//解密Token
var ticket = FormsAuthentication.Decrypt(token).UserData;
if (ticket.Equals("token示例"))
flag = true;
}
catch (Exception ex)
{ }
return flag;
}
#endregion #region 验证AppId
private bool IsAllowAppId(string appId)
{
var config = ConfigurationManager.GetSection("XryangConfig") as XryangConfig;
if (string.IsNullOrEmpty(appId) || string.IsNullOrEmpty(config.AppId)) return false;
if (appId.Equals(config.AppId)) return true;
return false;
}
#endregion
}
}

(2)在api控制器或方法上加上  [AuthorFilter] 即可

 using System;
using System.Net.Http.Formatting;
using System.Web.Http;
using System.Web.Security;
using Xryang.Api.Author;
using Xryang.Model.Commons; namespace Xryang.Api.Controllers
{
[AuthorFilter]
[RoutePrefix("Api/App")]
public class AppController : ApiController
{ #region 获取token
[Route("Token")]
[HttpPost]
public object Token()
{
var response = new ResponseModel
{
StatusCode = ,
Message = "很抱歉,系统出错了",
};
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(, "token示例", DateTime.Now,
DateTime.Now.AddHours(), true, "token示例",
FormsAuthentication.FormsCookiePath);
if (ticket != null)
{
var token = FormsAuthentication.Encrypt(ticket);
response.StatusCode = ;
response.Message = "获取成功";
response.Data = new { Secret = token };
}
return Json(response);
}
#endregion #region 参数声明示例·正确写法
[Route("Example")]
[HttpPost]
public object Example(FormDataCollection data)
{
var response = new ResponseModel
{
StatusCode = ,
Message = "接收数据成功!",
Data = data.Get("Name")
};
return Json(response);
}
#endregion
}
}