routeTemplate: "api/{controller}/{id}"

时间:2022-02-28 06:48:15

  身份验证(authentication)的责任是识别出http请求者的身份,除此之外尽量不要管其它的事。webapi的authentication我用authentication filter技术去解决。

参考资料:

  https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/authentication-filters

法式如下

创建authentication filter

  在项目里新建文件夹Security,并在此文件夹里创建IdentityBasicAuthentication类,代码如下

using System; using System.Threading; using System.Threading.Tasks; using System.Web.Http.Filters; namespace webapi.Security { public class IdentityBasicAuthentication:IAuthenticationFilter { public bool AllowMultiple { get; } public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken) { throw new NotImplementedException(); } } }

  担任自IauthenticationFilter,实现本身的业务代码(后面再实现)

注册authentication filter

  在webapi的config里插手filter,,改削项目代码如下

/// <summary> /// 返回webapi的httpconfiguration配置 /// 用于webapi应用于owin技术时使用 /// </summary> /// <returns></returns> public static HttpConfiguration OwinWebApiConfiguration(HttpConfiguration config) { config.MapHttpAttributeRoutes();//开启属性路由 config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); config.Filters.Add(new WebApiExceptionFilterAttribute()); config.Filters.Add(new IdentityBasicAuthentication()); return config; }

  即上一句:config.Filters.Add(new IdentityBasicAuthentication());