MVC—WebAPI(调用、授权)

ASP.NET MVC—WebAPI(调用、授权)

 

本系列目录:ASP.NET MVC4入门到精通系列目录汇总

微软有了Webservice和WCF,为什么还要有WebAPI?

用过WCF的人应该都清楚,面对那一大堆复杂的配置文件,有时候一出问题,真的会叫人抓狂。而且供不同的客户端调用不是很方便。不得不承认WCF的功能确实非常强大,可是有时候我们通常不需要那么复杂的功能,只需要简单的仅通过使用Http或Https来调用的增删改查功能,这时,WebAPI应运而生。那么什么时候考虑使用WebAPI呢?

当你遇到以下这些情况的时候,就可以考虑使用Web API了。

  • 需要Web Service但是不需要SOAP
  • 需要在已有的WCF服务基础上建立non-soap-based http服务
  • 只想发布一些简单的Http服务,不想使用相对复杂的WCF配置
  • 发布的服务可能会被带宽受限的设备访问
  • 希望使用开源框架,关键时候可以自己调试或者自定义一下框架

熟悉MVC的朋友你可能会觉得Web API 与MVC很类似。

Demo

1、新建项目,WebApi

2、新建类Product

复制代码
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Category { get; set; }
        public decimal Price { get; set; }
    }
复制代码

3、新建控制器Products,为了演示,我这里不连接数据库,直接代码中构造假数据

复制代码
using System.Net.Http;
using System.Web.Http;

public class ProductsController : ApiController { Product[] products = new Product[] { new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 }, new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M }, new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M } }; public IEnumerable<Product> GetAllProducts() { return products; } public IHttpActionResult GetProduct(int id) { var product = products.FirstOrDefault((p) => p.Id == id); if (product == null) { return NotFound(); } return Ok(product); } }
复制代码

4、新建Index.html来测试WebAPI的调用,代码如下:

 

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Product App</title>
</head>
<body>

<div>
<h2>All Products</h2>
<ul id="products" />
</div>
<div>
<h2>Search by ID</h2>
<input type="text" id="prodId" size="5" />
<input type="button" value="Search" onclick="find();" />
<p id="product" />
</div>

<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script>
var uri = 'api/products';

$(document).ready(function () {
$.getJSON(uri)
.done(function (data) {
$.each(data, function (key, item) {
$('<li>', { text: formatItem(item) }).appendTo($('#products'));
});
});
});

function formatItem(item) {
return item.Name + ': $' + item.Price;
}

function find() {
var id = $('#prodId').val();
$.getJSON(uri + '/' + id)
.done(function (data) {
$('#product').text(formatItem(data));
})
.fail(function (jqXHR, textStatus, err) {
$('#product').text('Error: ' + err);
});
}
</script>
</body>
</html>


运行结果如下:

WebAPI授权

1、新建授权过滤器类APIAuthorizeAttribute.cs

/* ==============================================================================
* 功能描述:APIAuthorizeAttribute
* 创 建 者:Zouqj
* 创建日期:2015/11/3 11:37:45
==============================================================================*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Http.Filters;
using Uuch.HP.WebAPI.Helper;

namespace Uuch.HP.WebAPI.Filter
{
public class APIAuthorizeAttribute : AuthorizationFilterAttribute
{
public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
{
//如果用户使用了forms authentication,就不必在做basic authentication了
if (Thread.CurrentPrincipal.Identity.IsAuthenticated)
{
return;
}

var authHeader = actionContext.Request.Headers.Authorization;

if (authHeader != null)
{
if (authHeader.Scheme.Equals("basic", StringComparison.OrdinalIgnoreCase) &&
!String.IsNullOrWhiteSpace(authHeader.Parameter))
{
var credArray = GetCredentials(authHeader);
var userName = credArray[0];
var key = credArray[1];
string ip = System.Web.HttpContext.Current.Request.UserHostAddress;
//if (IsResourceOwner(userName, actionContext))
//{
//You can use Websecurity or asp.net memebrship provider to login, for
//for he sake of keeping example simple, we used out own login functionality
if (APIAuthorizeInfoValidate.ValidateApi(userName,key,ip))//Uuch.HPKjy.Core.Customs.APIAuthorizeInfo.GetModel(userName, key, ip) != null
{
var currentPrincipal = new GenericPrincipal(new GenericIdentity(userName), null);
Thread.CurrentPrincipal = currentPrincipal;
return;
}
//}
}
}

HandleUnauthorizedRequest(actionContext);
}

private string[] GetCredentials(System.Net.Http.Headers.AuthenticationHeaderValue authHeader)
{

//Base 64 encoded string
var rawCred = authHeader.Parameter;
var encoding = Encoding.GetEncoding("iso-8859-1");
var cred = encoding.GetString(Convert.FromBase64String(rawCred));

var credArray = cred.Split(':');

return credArray;
}

private bool IsResourceOwner(string userName, System.Web.Http.Controllers.HttpActionContext actionContext)
{
var routeData = actionContext.Request.GetRouteData();
var resourceUserName = routeData.Values["userName"] as string;

if (resourceUserName == userName)
{
return true;
}
return false;
}

private void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
{
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);

actionContext.Response.Headers.Add("WWW-Authenticate",
"Basic Scheme='eLearning' location='http://localhost:8323/APITest'");

}
}
}

2、添加验证方法类APIAuthorizeInfoValidate.cs

using Newtonsoft.Json;
/* ==============================================================================
* 功能描述:APIAuthorizeInfoValidate
* 创 建 者:Zouqj
* 创建日期:2015/11/3 16:26:10
==============================================================================*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Uuch.HP.WebAPI.Helper
{
public class APIAuthorizeInfo
{
public string UserName { get; set; }
public string Key { get; set; }
}
public class APIAuthorizeInfoValidate
{
public static bool ValidateApi(string username, string key, string ip)
{
var _APIAuthorizeInfo = JsonConvert.DeserializeObject <List<APIAuthorizeInfo>>(WebConfigHelper.ApiAuthorize);
var ips = WebConfigHelper.IPs.Contains(",") ? WebConfigHelper.IPs.Split(',') : new string[] { WebConfigHelper.IPs };

if (_APIAuthorizeInfo != null && _APIAuthorizeInfo.Count > 0)
{
foreach (var v in _APIAuthorizeInfo)
{
if (v.UserName == username && v.Key == key && ips.Contains(ip))
{
return true;
}
}
}
return false;
}
}
}

3、把添加到全局过滤器中,这里要注意了,不要添加到FilterConfig.cs,而要添加到WebApiConfig.cs,因为FilterConfig是MVC用的,我们这里是WebAPI。

复制代码
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            config.Filters.Add(new APIAuthorizeAttribute());
        }
    }
复制代码

使用C#来调用WebAPI

以下用到的几个类,已经被我封装好了,可以直接使用。

1、新建webAPI站点,然后新建控制器RProducts

复制代码
  public class RProductsController : ApiController
    {
        /// <summary>
        /// 备案商品回执记录回调接口
        /// </summary>
        /// <param name="lst"></param>
        /// <returns></returns>
        public int Put(List<RProduct> lst)
        {
            return ReceiptInfo.UpdateReceiptProductInfo(lst);
        }
    }
复制代码

2、新建类WebApiClient.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using DBHelper.Entitys;

namespace DBHelper
{
public static class WebApiClient<T>
{
static void SetBasicAuthorization(HttpClient client)
{
HttpRequestHeaders header=client.DefaultRequestHeaders;
string user = ConfigHelper.UserName;
string key = ConfigHelper.Key;
Encoding encoding = Encoding.UTF8;
// Add an Accept header for JSON format.
// 为JSON格式添加一个Accept报头
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

//Base64编码
var data = Convert.ToBase64String(encoding.GetBytes(user + ":" + key));
//设置AuthenticationHeaderValue
header.Authorization = new AuthenticationHeaderValue("Basic", data);
//通过HttpRequestHeaders.Add
//header.Add("Authorization", "Basic " + data);
}
public static List<T> GetAll(string url)
{
List<T> li = new List<T>();
HttpClient client = new HttpClient();
SetBasicAuthorization(client);
// List all products.
// 列出所有产品
HttpResponseMessage response = client.GetAsync(url).Result;// Blocking call(阻塞调用)!
if (response.IsSuccessStatusCode)
{
// Parse the response body. Blocking!
// 解析响应体。阻塞!
li = response.Content.ReadAsAsync<List<T>>().Result;
}
else
{
Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
}
return li;
}

public static T GetByFilter(string url)
{
T entity = default(T);
HttpClient client = new HttpClient();
SetBasicAuthorization(client);
// List all products.
// 列出所有产品
HttpResponseMessage response = client.GetAsync(url).Result;// Blocking call(阻塞调用)!
if (response.IsSuccessStatusCode)
{
// Parse the response body. Blocking!
// 解析响应体。阻塞!
entity = response.Content.ReadAsAsync<T>().Result;
}
return entity;
}

public static T Get(string url,string id)
{
T entity=default(T);
HttpClient client = new HttpClient();
SetBasicAuthorization(client);
// List all products.
// 列出所有产品
HttpResponseMessage response = client.GetAsync(string.Format("{0}/{1}",url,id)).Result;// Blocking call(阻塞调用)!
if (response.IsSuccessStatusCode)
{
// Parse the response body. Blocking!
// 解析响应体。阻塞!
entity = response.Content.ReadAsAsync<T>().Result;
}
return entity;
}

public static bool Edit(string url,List<int> value)
{
HttpClient client = new HttpClient();
SetBasicAuthorization(client);
var response = client.PutAsJsonAsync(url,value).Result;
if (response.IsSuccessStatusCode)
{
return true;
}
else
{
return false;
}
}
public static bool Edit(string url, Dictionary<int, string> dic)
{
HttpClient client = new HttpClient();
SetBasicAuthorization(client);
var response = client.PutAsJsonAsync(url, dic).Result;
if (response.IsSuccessStatusCode)
{
return true;
}
else
{
return false;
}
}
public static bool EditModel(string url, List<T> value)
{
HttpClient client = new HttpClient();
SetBasicAuthorization(client);
var response = client.PutAsJsonAsync(url, value).Result;
if (response.IsSuccessStatusCode)
{
return true;
}
else
{
return false;
}
}

public static List<TI> GetList<TI>(string url, List<int> value)
{
List<TI> list = new List<TI>();
HttpClient client = new HttpClient();
SetBasicAuthorization(client);
var response = client.PostAsJsonAsync(url, value).Result;
if (response.IsSuccessStatusCode)
{
list = response.Content.ReadAsAsync<List<TI>>().Result;
}
else
{
list = new List<TI>();
}
return list;
}
}
}

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using DBHelper.Entitys;

namespace DBHelper
{
    public static class WebApiClient<T>
    {
        static void SetBasicAuthorization(HttpClient client)
        {
            HttpRequestHeaders header=client.DefaultRequestHeaders;
            string user = ConfigHelper.UserName;
            string key = ConfigHelper.Key;
            Encoding encoding = Encoding.UTF8;
            // Add an Accept header for JSON format.
            // 为JSON格式添加一个Accept报头
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
           
            //Base64编码
            var data = Convert.ToBase64String(encoding.GetBytes(user + ":" + key));
            //设置AuthenticationHeaderValue
            header.Authorization = new AuthenticationHeaderValue("Basic", data);
            //通过HttpRequestHeaders.Add
            //header.Add("Authorization", "Basic " + data);
        }
        public static List<T> GetAll(string url)
        {
            List<T> li = new List<T>();
            HttpClient client = new HttpClient();
            SetBasicAuthorization(client);
            // List all products.
            // 列出所有产品
            HttpResponseMessage response = client.GetAsync(url).Result;// Blocking call(阻塞调用)! 
            if (response.IsSuccessStatusCode)
            {
                // Parse the response body. Blocking!
                // 解析响应体。阻塞!
                li = response.Content.ReadAsAsync<List<T>>().Result;
            }
            else
            {
                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            }
            return li;
        }

        public static T GetByFilter(string url)
        {
            T entity = default(T);
            HttpClient client = new HttpClient();
            SetBasicAuthorization(client);
            // List all products.
            // 列出所有产品
            HttpResponseMessage response = client.GetAsync(url).Result;// Blocking call(阻塞调用)! 
            if (response.IsSuccessStatusCode)
            {
                // Parse the response body. Blocking!
                // 解析响应体。阻塞!
                entity = response.Content.ReadAsAsync<T>().Result;
            }
            return entity;
        }

        public static T Get(string url,string id)
        {
            T entity=default(T);
            HttpClient client = new HttpClient();
            SetBasicAuthorization(client);
            // List all products.
            // 列出所有产品
            HttpResponseMessage response = client.GetAsync(string.Format("{0}/{1}",url,id)).Result;// Blocking call(阻塞调用)! 
            if (response.IsSuccessStatusCode)
            {
                // Parse the response body. Blocking!
                // 解析响应体。阻塞!
                entity = response.Content.ReadAsAsync<T>().Result;
            }
            return entity;
        }

        public static bool Edit(string url,List<int> value)
        {         
            HttpClient client = new HttpClient();
            SetBasicAuthorization(client);
            var response = client.PutAsJsonAsync(url,value).Result;
            if (response.IsSuccessStatusCode)
            {              
                return true;
            }
            else
            {
                return false;
            }
        }
        public static bool Edit(string url, Dictionary<int, string> dic)
        {
            HttpClient client = new HttpClient();
            SetBasicAuthorization(client);
            var response = client.PutAsJsonAsync(url, dic).Result;
            if (response.IsSuccessStatusCode)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        public static bool EditModel(string url, List<T> value)
        {
            HttpClient client = new HttpClient();
            SetBasicAuthorization(client);
            var response = client.PutAsJsonAsync(url, value).Result;
            if (response.IsSuccessStatusCode)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public static List<TI> GetList<TI>(string url, List<int> value)
        {
            List<TI> list = new List<TI>();
            HttpClient client = new HttpClient();
            SetBasicAuthorization(client);
            var response = client.PostAsJsonAsync(url, value).Result;
            if (response.IsSuccessStatusCode)
            {
                list = response.Content.ReadAsAsync<List<TI>>().Result;                
            }
            else
            {
                list = new List<TI>();
            }
            return list;
        }
    }
}
复制代码

3、新建类BaseEntity.cs

 

using NHibernate;
using NHibernate.Criterion;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Common;
using System.Linq;
using System.Text;

namespace DBHelper
{
public abstract class BaseEntity<T, TID> where T : BaseEntity<T, TID>
{
#region 属性
/// <summary>
/// 编号
/// </summary>
public string V_PreInvtId { get; set; }
/// <summary>
/// 回执状态
/// </summary>
public int V_OpResult { get; set; }
/// <summary>
/// 操作时间
/// </summary>
public DateTime D_optime { get; set; }
/// <summary>
/// 备注
/// </summary>
public string V_NoteS { get; set; }
#endregion
public virtual TID ID { get; set; }

#region
/// <summary>
/// Session配置文件路径
/// </summary>
protected static readonly string SessionFactoryConfigPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "NHibernate.config");

/// <summary>
/// 返回对应的Session.
/// </summary>
protected static ISession NHibernateSession
{
get
{
return NHibernateSessionManager.Instance.GetSessionFrom(SessionFactoryConfigPath);
}
}
#endregion

#region common
/// <summary>
/// 根据ID从数据库获取一个类型为T的实例
/// </summary>
public static T GetById(TID id, bool shouldLock)
{
T entity;

if (shouldLock)
{
entity = NHibernateSession.Get<T>(id, LockMode.Upgrade);
}
else
{
entity = NHibernateSession.Get<T>(id);
}

return entity;
}

/// <summary>
/// 根据ID从数据库获取一个类型为T的实例
/// </summary>
public static T GetById(TID id)
{
return GetById(id, false);
}

/// <summary>
/// 获取所有的类型为T的对象
/// </summary>
public static IList<T> GetAll()
{
return GetByCriteria();
}

/// <summary>
/// 根据给定的 <see cref="ICriterion" /> 来查询结果
/// 如果没有传入 <see cref="ICriterion" />, 效果与 <see cref="GetAll" />一致.
/// </summary>
public static IList<T> GetByCriteria(params ICriterion[] criterion)
{
ICriteria criteria = NHibernateSession.CreateCriteria(typeof(T));

foreach (ICriterion criterium in criterion)
{
criteria.Add(criterium);
}
criteria.AddOrder(new Order("ID", false));
return criteria.List<T>();
}
#endregion

#region entity
/// <summary>
/// 根据exampleInstance的属性值来查找对象,返回与其值一样的对象对表。
/// exampleInstance中值为0或NULL的属性将不做为查找条件
/// </summary>
/// <param name="exampleInstance">参考对象</param>
/// <param name="propertiesToExclude">要排除的查询条件属性名</param>
/// <returns></returns>
public virtual IList<T> GetByExample(T exampleInstance, params string[] propertiesToExclude)
{
ICriteria criteria = NHibernateSession.CreateCriteria(exampleInstance.GetType());
Example example = Example.Create(exampleInstance);

foreach (string propertyToExclude in propertiesToExclude)
{
example.ExcludeProperty(propertyToExclude);
}
example.ExcludeNone();
example.ExcludeNulls();
example.ExcludeZeroes();
criteria.Add(example);
criteria.AddOrder(new Order("ID", false));
return criteria.List<T>();
}

/// <summary>
/// 使用<see cref="GetByExample"/>来返回一个唯一的结果,如果结果不唯一会抛出异常
/// </summary>
/// <exception cref="NonUniqueResultException" />
public virtual T GetUniqueByExample(T exampleInstance, params string[] propertiesToExclude)
{
IList<T> foundList = GetByExample(exampleInstance, propertiesToExclude);

if (foundList.Count > 1)
{
throw new NonUniqueResultException(foundList.Count);
}

if (foundList.Count > 0)
{
return foundList[0];
}
else
{
return default(T);
}
}

/// <summary>
/// 将指定的对象保存到数据库,并立限提交,并返回更新后的ID
/// See http://www.hibernate.org/hib_docs/reference/en/html/mapping.html#mapping-declaration-id-assigned.
/// </summary>
//public virtual T Save()
//{
// T entity = (T)this;
// NHibernateSession.Save(entity);
// NHibernateSession.Flush();
// return entity;
//}

/// <summary>
/// 将指定的对象保存或更新到数据库,并返回更新后的ID
/// </summary>
//public virtual T Merge()
//{
// T entity = (T)this;
// NHibernateSession.Merge<T>(entity);
// NHibernateSession.Flush();
// return entity;
//}

///// <summary>
///// 从数据库中删除指定的对象
///// </summary>
//public virtual void Delete()
//{
// T entity = (T)this;
// NHibernateSession.Delete(entity);
// NHibernateSession.Flush();
//}

public virtual DbTransaction BeginTransaction()
{
ITransaction tran = NHibernateSession.BeginTransaction();// NHibernateSessionManager.Instance.BeginTransactionOn(SessionFactoryConfigPath);
return new DbTransaction(tran);
}

/// <summary>
/// 提交所有的事务对象,并Flush到数据库
/// </summary>
public virtual void CommitChanges()
{
if (NHibernateSessionManager.Instance.HasOpenTransactionOn(SessionFactoryConfigPath))
{
NHibernateSessionManager.Instance.CommitTransactionOn(SessionFactoryConfigPath);
}
else
{
// 如果不是事务模式,就直接调用Flush来更新
NHibernateSession.Flush();
}
}
#endregion

#region WebApi获取数据
public static string Url
{
get
{
string url = System.Configuration.ConfigurationManager.AppSettings[typeof(T).Name];
if (string.IsNullOrEmpty(url))
{
throw new Exception(string.Format("“{0}”未包含URL配置", typeof(T).Name));
}
return url;
}
}

public static List<T> GetAllBySource()
{
return WebApiClient<T>.GetAll(Url);
}

public static void EditBySource(List<int> value)
{
WebApiClient<T>.Edit(Url, value);
}
public static void EditBySource(Dictionary<int, string> dic)
{
WebApiClient<T>.Edit(Url, dic);
}
public static T GetOneBySource(string id)
{
return WebApiClient<T>.Get(Url, id);
}
public static void EditBySourceByModel(List<T> value)
{
WebApiClient<T>.EditModel(Url, value);
}
#endregion
}

public class DbTransaction : IDisposable
{
ITransaction _transaction;

public DbTransaction(ITransaction transaction)
{

_transaction = transaction;
}

#region IDisposable 成员

public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}

protected virtual void Dispose(bool disposing)
{
if (disposing)
{
_transaction.Dispose();
_transaction = null;
}
}

#endregion

#region ITransaction 成员

public void Begin(System.Data.IsolationLevel isolationLevel)
{
_transaction.Begin(isolationLevel);
}

public void Begin()
{
_transaction.Begin();
}

public void Commit()
{
_transaction.Commit();
}

public void Enlist(System.Data.IDbCommand command)
{
_transaction.Enlist(command);
}

public bool IsActive
{
get { return _transaction.IsActive; }
}

public void RegisterSynchronization(NHibernate.Transaction.ISynchronization synchronization)
{
_transaction.RegisterSynchronization(synchronization);
}

public void Rollback()
{
_transaction.Rollback();
}

public bool WasCommitted
{
get { return _transaction.WasCommitted; }
}

public bool WasRolledBack
{
get { return _transaction.WasRolledBack; }
}

#endregion
}
}

4、调用代码:

       List<EProducts> list = DBHelper.Entitys.EProducts.GetAllBySource();

在调用WebAPI之前,记得先运行WebAPI站点。

当我们的WebAPI站点开发完成之后,我们可以使用Nuget安装一个插件自动生成API文档,这个插件同时还支持WebAPI在线测试的。

复制代码
/* ==============================================================================
   * 功能描述:APIAuthorizeAttribute  
   * 创 建 者:Zouqj
   * 创建日期:2015/11/3 11:37:45
   ==============================================================================*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Http.Filters;
using Uuch.HP.WebAPI.Helper;

namespace Uuch.HP.WebAPI.Filter
{
    public class APIAuthorizeAttribute : AuthorizationFilterAttribute
    {
        public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            //如果用户使用了forms authentication,就不必在做basic authentication了
            if (Thread.CurrentPrincipal.Identity.IsAuthenticated)
            {
                return;
            }

            var authHeader = actionContext.Request.Headers.Authorization;

            if (authHeader != null)
            {
                if (authHeader.Scheme.Equals("basic", StringComparison.OrdinalIgnoreCase) &&
                    !String.IsNullOrWhiteSpace(authHeader.Parameter))
                {
                    var credArray = GetCredentials(authHeader);
                    var userName = credArray[0];
                    var key = credArray[1];
                    string ip = System.Web.HttpContext.Current.Request.UserHostAddress;
                    //if (IsResourceOwner(userName, actionContext))
                    //{
                        //You can use Websecurity or asp.net memebrship provider to login, for
                        //for he sake of keeping example simple, we used out own login functionality
                    if (APIAuthorizeInfoValidate.ValidateApi(userName,key,ip))//Uuch.HPKjy.Core.Customs.APIAuthorizeInfo.GetModel(userName, key, ip) != null
                        {
                            var currentPrincipal = new GenericPrincipal(new GenericIdentity(userName), null);
                            Thread.CurrentPrincipal = currentPrincipal;
                            return;
                        }
                   //}
                }
            }

            HandleUnauthorizedRequest(actionContext);
        }

        private string[] GetCredentials(System.Net.Http.Headers.AuthenticationHeaderValue authHeader)
        {

            //Base 64 encoded string
            var rawCred = authHeader.Parameter;
            var encoding = Encoding.GetEncoding("iso-8859-1");
            var cred = encoding.GetString(Convert.FromBase64String(rawCred));

            var credArray = cred.Split(':');

            return credArray;
        }

        private bool IsResourceOwner(string userName, System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            var routeData = actionContext.Request.GetRouteData();
            var resourceUserName = routeData.Values["userName"] as string;

            if (resourceUserName == userName)
            {
                return true;
            }
            return false;
        }

        private void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);

            actionContext.Response.Headers.Add("WWW-Authenticate",
                                               "Basic Scheme='eLearning' location='http://localhost:8323/APITest'");

        }
    }
}
复制代码
原文地址:https://www.cnblogs.com/Leo_wl/p/4934058.html