国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > .NET > 正文

ASP.NET MVC API 接口驗(yàn)證的示例代碼

2024-07-10 12:48:57
字體:
供稿:網(wǎng)友

項(xiàng)目中有一個留言消息接口,接收其他系統(tǒng)的留言和展示留言,參考了網(wǎng)上的一些API驗(yàn)證方法,發(fā)現(xiàn)使用通用權(quán)限管理系統(tǒng)提供的驗(yàn)證方法最完美。

下面將實(shí)現(xiàn)的完整思路共享

1、WebApiConfig全局處理

/// <summary>  /// WebApiConfig   /// 路由基礎(chǔ)配置。  ///   ///   /// 修改記錄  ///   ///    2016.11.01 版本:2.0 宋彪 對日期格式進(jìn)行統(tǒng)一處理。  ///    2016.10.30 版本:2.0 宋彪 解決json序列化時的循環(huán)引用問題。  ///    2016.10.28 版本:2.0 宋彪 回傳響應(yīng)格式 $format 支持。  ///    2016.09.01 版本:1.0 宋彪  創(chuàng)建。  ///   /// 版本:1.0  ///   /// <author>  ///    <name>宋彪</name>  ///    <date>2016.09.01</date>  /// </author>   /// </summary>  public static class WebApiConfig  {    /// <summary>    /// 注冊全局配置服務(wù)    /// </summary>    /// <param name="config"></param>    public static void Register(HttpConfiguration config)    {      // Web API configuration and services      //強(qiáng)制https訪問      //config.Filters.Add(new ForceHttpsAttribute());      // 統(tǒng)一回傳格式      config.Filters.Add(new ApiResultAttribute());      // 發(fā)生異常時處理      config.Filters.Add(new ApiErrorHandleAttribute());      // ToKen身份驗(yàn)證過濾器 更方便 不需要在這里了 具有改標(biāo)簽的就會自動檢查      //config.Filters.Add(new ApiAuthFilterAttribute());      // 解決json序列化時的循環(huán)引用問題      config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;      //對日期格式進(jìn)行統(tǒng)一處理      config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(      new IsoDateTimeConverter()      {        DateTimeFormat = "yyyy-MM-dd hh:mm:ss"      }      );      // Web API routes 路由      config.MapHttpAttributeRoutes();      config.Routes.MapHttpRoute(        name: "DefaultApi",        routeTemplate: "api/{controller}/{action}/{id}",        defaults: new { id = RouteParameter.Optional }      );      // 干掉XML序列化器      //config.Formatters.Remove(config.Formatters.XmlFormatter);      //在請求的Url加上 ?$format=xml,便可以指定響應(yīng)格式      config.Formatters.XmlFormatter.AddQueryStringMapping("$format", "xml", "application/xml");      config.Formatters.JsonFormatter.AddQueryStringMapping("$format", "json", "application/json");    }  }

2、身份驗(yàn)證過濾器

  using DotNet.Business;  using DotNet.Utilities;  using DotNet.Tracking.API.Common;  /// <summary>  /// ApiAuthFilterAttribute  /// 身份驗(yàn)證過濾器,具有ApiAuthFilterAttribute標(biāo)簽屬性的方法會自動檢查  ///   ///   /// 修改紀(jì)錄  ///   /// 2016-10-11 版本:1.0 SongBiao 創(chuàng)建文件。    ///   /// <author>  ///   <name>SongBiao</name>  ///   <date>2016-10-11</date>  /// </author>  /// </summary>  [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]  public class ApiAuthFilterAttribute : AuthorizationFilterAttribute  {    /// <summary>    /// 未授權(quán)時的提示信息    /// </summary>    private const string UnauthorizedMessage = "請求未授權(quán),拒絕訪問。";    /// <summary>    /// 權(quán)限進(jìn)入    /// </summary>    /// <param name="actionContext"></param>    public override void OnAuthorization(HttpActionContext actionContext)    {      base.OnAuthorization(actionContext);      // 允許匿名訪問      if (actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Count > 0)       {        return;      }      string systemCode = APIOperateContext.Current.SystemCode;      string permissionCode = APIOperateContext.Current.PermissionCode;      string appKey = APIOperateContext.Current.AppKey;      string appSecret = APIOperateContext.Current.AppSecret;            if (string.IsNullOrWhiteSpace(appKey) || string.IsNullOrWhiteSpace(appSecret))      {        //未驗(yàn)證(登錄)的用戶, 而且是非匿名訪問,則轉(zhuǎn)向登錄頁面         //actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);        //actionContext.Response.Content = new StringContent("<p>Unauthorized</p>", Encoding.UTF8, "text/html");        var response = actionContext.Response= actionContext.Response?? new HttpResponseMessage();        response.StatusCode = HttpStatusCode.Unauthorized;        BaseResult result = new BaseResult        {          Status = false,          StatusMessage = UnauthorizedMessage        };        response.Content = new StringContent(result.ToJson(), Encoding.UTF8, "application/json");      }      else      {        // 檢查 AppKey 和 AppSecret        BaseResult result = BaseServicesLicenseManager.CheckService(appKey, appSecret, false, 0, 0, systemCode, permissionCode);        if (!result.Status)        {          var response = actionContext.Response = actionContext.Response?? new HttpResponseMessage();          response.Content = new StringContent(result.ToJson(), Encoding.UTF8, "application/json");        }      }               }  }            
發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 泸州市| 安陆市| 井研县| 台湾省| 邵阳县| 富宁县| 即墨市| 买车| 荔浦县| 昆明市| 天全县| 龙门县| 石泉县| 罗定市| 连云港市| 甘南县| 尉犁县| 漾濞| 巨野县| 刚察县| 京山县| 巴塘县| 河东区| 田阳县| 离岛区| 岱山县| 江门市| 曲靖市| 从江县| 大港区| 汕尾市| 磐安县| 三江| 博乐市| 思南县| 修武县| 宁河县| 南川市| 肇源县| 民乐县| 桐城市|