C# MVC api

//api

using System.Web.Http;
using System.Net;
using System.Net.Http;
	[HttpPost]
        public HttpResponseMessage Add(ViewModels.Api.Apply vmodel)
        {
            HttpResponseMessage httpResponse = null;
            try
            {
                ApplySimple apply = new ApplySimple()
                {
                    Name = vmodel.Name,
                    Sex = vmodel.Sex,
                    AddDate = vmodel.AddDate
                };
                new ZacApplySimpleService().Add(apply);
                httpResponse = new HttpResponseMessage(HttpStatusCode.OK);
                httpResponse.Content = new StringContent(apply.Id);
            }
            catch
            {
                httpResponse = new HttpResponseMessage(HttpStatusCode.ExpectationFailed);
            }

            return httpResponse;
	}

	[HttpGet]
	public HttpResponseMessage Get(string id) { ... }


//请求
	var content = new FormUrlEncodedContent(new[]{
		      new KeyValuePair<string,string>("Name",emCustomer.Name),
                      new KeyValuePair<string,string>("Sex",emCustomer.Sex.HasValue ? emCustomer.Sex.Value.ToString() : null),
                      new KeyValuePair<string,string>("AddDate",DateTime.Now.ToString())
	});
	HttpClient httpClient = new HttpClient();
	HttpResponseMessage httpRespMsg = httpClient.PostAsync(EsdApiURL.ZaWebUrl + "/api/apply/add", content).Result;
	if (httpRespMsg.IsSuccessStatusCode)
	{
	    string applyId = httpRespMsg.Content.ReadAsStringAsync().Result;
	    ...
	}

 

config.TokenKey = "EsdApi-Access-Token"
config.TokenValue = "fc85a7ce091aea86ef3463b9166e9b06" //md5("123456ABCDE")
config.AccessKeyName = "EsdApi-Access-Key"
config.AccessValueName = "EsdApi-Access-Value"


using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;

    public class DmOverrideHttpClientHandler : HttpClientHandler
    {
	// 测试用的
        private string EsdApi_AccessKey = null;//identity -> { id:"",name:"",... }
        private string EsdApi_AccessValue = null;//AES(oc_guid:MD5(identity))

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            request.Headers.Accept.Clear();
            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            request.Headers.Add(config.TokenKey, config.TokenValue); //md5("123456ABCDE")
            if (EsdApi_AccessKey != null && EsdApi_AccessValue != null)
            {
                request.Headers.Add(config.AccessKeyName, "..."); //identity.id
                request.Headers.Add(config.AccessValueName, "..."); //AES(oc_guid:MD5(identity))
            }
            var task = base.SendAsync(request, cancellationToken);
            var response = task.Result;

            /*MediaTypeHeaderValue contentType = response.Content.Headers.ContentType;
            if (contentType != null && string.IsNullOrEmpty(contentType.CharSet))
            {
                contentType.CharSet = "GBK";
            }*/

            return task;
        }
    }


调用:
        private DmOverrideHttpClientHandler httpclientHandler = new DmOverrideHttpClientHandler();
	HttpClient hc = new HttpClient(httpclientHandler);
        var httpResp = hc.GetAsync(...
	var httpResp2 = hc.PostAsync(...













//Api安全验证: AES(oc_guid:MD5(identity))

	WebApiConfig 
	config.Filters.Add(new AccessGuard());


    public class AccessGuard : AuthorizeAttribute
    {
        public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            var headers = actionContext.Request.Headers;
            if (!headers.Contains(config.TokenKey))
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Unauthorized)
                {
                    Content = new StringContent("Request is missing authorization token.")
                });
            }
            var requestToken = headers.GetValues(config.TokenKey).First();
            if (requestToken != config.TokenValue) //md5("123456ABCDE")
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Unauthorized)
                {
                    Content = new StringContent("Invalid identity failed.")
                });
            }

            IsAuthorized(actionContext);

            if (headers.Contains(config.AccessKeyName) && headers.Contains(config.AccessValueName))
            {
                string accessKey = headers.GetValues(config.AccessKeyName).First(); //identity.id
                string accessValue = headers.GetValues(config.AccessValueName).First(); //AES(oc_guid:MD5(identity))

                if !(accessKey是服务端下发的 && AESDecrypt(accessValue).oc_guid没有重访问 && AESDecrypt(accessValue).MD5(identity)服务端存在)
                {
                    throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Unauthorized)
                    {
                        Content = new StringContent("Invalid identity failed.")
                    });
                }
            }
        }


[AccessGuard]
public HttpResponseMessage Method(){...





public class ActionFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            base.OnActionExecuting(actionContext);
        }

        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            if (Thread.CurrentPrincipal.Identity is ApiIdentity)
            {
                ApiIdentity identity = (ApiIdentity)Thread.CurrentPrincipal.Identity;
                if (identity.IsAuthenticated)
                {
                    identity.Expirs = DateTime.Now.AddHours(1);
                    GlobalData.identityStore.UpdateExpirs(identity);
                    actionExecutedContext.Response.Headers.Add("UpdateExpirs", identity.Expirs.ToString("yyyy-MM-dd HH:mm:ss"));
                }
            }
            base.OnActionExecuted(actionExecutedContext);
        }
    }


[DataContract]
public class ApiIdentity : IIdentity
{
        [DataMember]
        public string Id { get; set; }
        [DataMember]
        public string Name { get; set; }

	[DataMember]
        public string Mobile { get; set; }
        
        public DateTime Expirs { get; set; }

        public string AuthenticationType
        {
            get { return "Custom"; }
        }

        public bool IsAuthenticated
        {
            get { return true; }
        }
}


    public class ApiPrincipal : IPrincipal
    {
        private readonly ApiIdentity m_ApiIdentity;
        public ApiPrincipal(ApiIdentity identity)
        {
            m_ApiIdentity = identity;
        }
        public IIdentity Identity
        {
            get
            {
                return m_ApiIdentity;
            }
        }
        public string Role { get; set; }
        public bool IsInRole(string role)
        {
            return Role == role;
        }
    }


public class IdentityStore
{

私有成员...

构造函数...
public IdentityStore()
        {
            new Thread(() =>
            {
                Thread.Sleep(1000 * 60 * 60);
                identities.RemoveAll(m => m.Expirs < DateTime.Now);
            }).Start();
        }

验证身份...

新增身份...

移除身份...

更新过期时间...

        //设置认证信息
        public void SetPrincipal(ApiIdentity _identity)
        {
            ApiPrincipal principal = new ApiPrincipal(_identity);
            Thread.CurrentPrincipal = principal;
            HttpContext.Current.User = principal;
        }
}

if (!(Thread.CurrentPrincipal.Identity is ApiIdentity))...

string customerId=((ApiIdentity)apiController.User.Identity).Id;




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值