1.Filter文件夹下添加如下BasicAuthorizeAttribute 类;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Http;
using System.Web.Security;
namespace ABBPMP.WebApi.Filter
{
/// <summary>
/// 自定义此特性用于接口的身份验证
/// </summary>
public class BasicAuthorizeAttribute : AuthorizeAttribute
{
//重写基类的验证方式,加入我们自定义的Ticket验证
public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
{
//从http请求的头里面获取身份验证信息,验证是否是请求发起方的ticket
var authorization = actionContext.Request.Headers.Authorization;
if ((authorization != null) && (authorization.Parameter != null))
{
//解密用户ticket,并校验用户名密码是否匹配
var encryptTicket = authorization.Parameter;
if (ValidateTicket(encryptTicket))
{
base.IsAuthorized(actionContext);
}
else
{
HandleUnauthorizedRequest(actionContext);
}
}
//如果取不到身份验证信息,并且不允许匿名访问,则返回未验证401
else
{
var attributes = actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().OfType<AllowAnonymousAttribute>();
bool isAnonymous = attributes.Any(a => a is AllowAnonymousAttribute);
if (isAnonymous)
base.OnAuthorization(actionContext);
else
HandleUnauthorizedRequest(actionContext);
}
}
//校验用户名密码(正式环境中应该是数据库校验)
private bool ValidateTicket(string encryptTicket)
{
//解密Ticket
var strTicket = Encoding.Default.GetString(Convert.FromBase64String(encryptTicket));
//从Ticket里面获取用户名和密码
var index = strTicket.IndexOf(":");
string strUser = strTicket.Substring(0, index);
string strPwd = strTicket.Substring(index + 1);
if (strUser == "name" && strPwd == "password")
{
return true;
}
else
{
return false;
}
}
}
}
2.WebApi添加以上字段属性(可以整个类添加,也可以只加在对应的方法上)
[BasicAuthorizeAttribute]
public class PlanController : BaseApiController
{
......
}
3.WebApi调用
public static void APITest()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:4765/");
var url = $"api/xxx/xxx?so=12312345&ci=1000";
AuthenticationHeaderValue authentication = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(Encoding.UTF8.GetBytes($"name:password")));
client.DefaultRequestHeaders.Authorization = authentication;
var resultStr = client.GetAsync(url).Result.Content.ReadAsStringAsync().Result;
if (resultStr != null)
{
//var result = JsonConvert.DeserializeObject<Models.ResultModel>(resultStr);
}
return;
}
标签:WebApi,Web,C#,System,Basic,var,using,actionContext From: https://www.cnblogs.com/jxw-29/p/17292226.html