C#编程之C#调用接口接收结果【Get,Post通用】
小标
2018-11-27
来源 :
阅读 2362
评论 0
摘要:本文主要向大家介绍了C#编程之C#调用接口接收结果【Get,Post通用】,通过具体的内容向大家展示,希望对大家学习C#编程有所帮助。
本文主要向大家介绍了C#编程之C#调用接口接收结果【Get,Post通用】,通过具体的内容向大家展示,希望对大家学习C#编程有所帮助。
1.首先,客户端调用接口的实例
1.1 先定义接收接口结果类
public class ResultMsg
{
public bool title { get; set; }
public string message { get; set; }
public string other { get; set; }
}
1.2 以用户登陆为例,登陆时请求接口输入参数用户名密码判断是否正确
public static ResultMsg CheckLogin(string account,string pwd)
{
// Tools.Common1.WriteLog("checklogin", "checklogin", "account:" + account + "----pwd:" + pwd);
WebApiResult msg = WebApiHelper.GetWebApi(new { UserName = account, PassWord = pwd }, "/UserAccounts/Login/");
if (msg.Success)
{
return msg.result;
}
else
{
return new ResultMsg() { title = false, message = "请求接口失败,"+msg.result.message };
}
}
调用接口处,在header里添加访问的账号密码来提升接口的安全度
private const string pwd = "abc_2015?";
private const string account = "webaccount";
#region 请求webapi
///
/// 请求webapi
///
///
///
///
public static WebApiResult GetWebApi(object model, string path)
{
WebClient wc = new WebClient();
wc.Headers.Add(HttpRequestHeader.Accept, "application/json");
wc.Headers.Add(HttpRequestHeader.ContentType, "application/json; charset=utf-8");
string auth = AuthorizationHelper.GetAuthorization1(account, path, pwd);
wc.Headers.Add(HttpRequestHeader.Authorization,auth);
byte[] postData = System.Text.Encoding.UTF8.GetBytes(new JavaScriptSerializer().Serialize(model));
try
{
byte[] text = wc.UploadData(domain + path, "post", postData);
string str = System.Text.Encoding.UTF8.GetString(text);
return new JavaScriptSerializer().Deserialize
(str);
}
catch(Exception ex){
return new WebApiResult() { Success = false, result = new ResultMsg() { title = false, message = ex.Message } };
}
}
#endregion
}
1.3接口在另一个项目中,实例如下:
在接口项目的app_start文件夹下,新建类LoginAttribute来判别header里传输的账号密码是否正确
//标示该特性能用于类、方法,特性不能被重复放置在同一个程序实体前多次
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public class LoginAttribute : ActionFilterAttribute
{
///
/// 在action执行前
///
///
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
//过滤器上下文为空,抛出异常
if (filterContext == null)
{
throw new ArgumentException("filterContext");
}
//获取访问路径、账号、时间戳、密文
var path = filterContext.HttpContext.Request.Path.ToString();
var authorization = filterContext.HttpContext.Request.Headers["Authorization"];
if (!string.IsNullOrEmpty(authorization))
{
//分割验证字符串, account,mac,salt
string[] strs = authorization.Split(‘,‘);
if (strs.Length == 3)
{
string account = strs[0].Replace("account=", "");
var mac = strs[1].Replace("mac=", "");
var salt = strs[2].Replace("salt=", "");
if (!string.IsNullOrEmpty(account))
{
try
{
var pwd = System.Configuration.ConfigurationManager.AppSettings[account].ToString();
string ciphertext = Uri.EscapeDataString(PISCenter.Common.Utility.GetCiphertext(account, path, salt, pwd));
if (ciphertext.Equals(mac))
{
base.OnActionExecuting(filterContext);
}
}
catch
{
filterContext.Result = new JsonResult { Data = new { title = false, message = "认证错误,拒绝访问" }, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
else
{
filterContext.Result = new JsonResult { Data = new { title = false, message = "认证错误,拒绝访问" }, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
else
{
filterContext.Result = new JsonResult { Data = new { title = false, message = "认证错误,拒绝访问" }, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
else {
filterContext.Result = new JsonResult { Data = new { title = false, message = "认证错误,拒绝访问" }, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
}
1.4 登陆的方法体
[HttpPost]
public JsonResult Login(CheckLoginInput model)
{
if (model == null||string.IsNullOrEmpty(model.PassWord)||(string.IsNullOrEmpty(model.UserName)&&string.IsNullOrEmpty(model.MobilePhone)))
{
return Fail("提交参数不正确");
}
CheckLoginOutPut ua=_useraccountsAppService.CheckLogin(model);
if (ua!=null&&ua.Id>0)
{
return Success(Newtonsoft.Json.JsonConvert.SerializeObject(ua));
}
else {
return Fail("登录失败,账号或密码错误");
}
}
整个流程结束
附:项目里
public static string GetAuthorization1(string account, string path,string password)
{
StringBuilder sb = new StringBuilder();
string date=Uri.EscapeDataString(GetTimeStamp());
sb.AppendFormat("account={0},mac={1},salt={2}", Uri.EscapeDataString(account), Uri.EscapeDataString(GetCiphertext(account, path, date,password)), date);
return sb.ToString();
}
接口项目里:
///
/// 对访问者进行SHA-1加密,返回加密的密文
///
/// 账号
/// 访问路径 /开头,/结尾
/// 时间戳
/// 密码
///
public static string GetCiphertext(string account, string path, string date, string password)
{
string ciphertext = account + "\n" + date + "\n" + path.ToLower() + "\n" + password + "\n";
System.Security.Cryptography.HMACSHA1 hmacsha1 = new System.Security.Cryptography.HMACSHA1();
hmacsha1.Key = Encoding.UTF8.GetBytes(password);
byte[] dataBuffer = Encoding.UTF8.GetBytes(ciphertext);
byte[] hashBytes = hmacsha1.ComputeHash(dataBuffer);
ciphertext = Convert.ToBase64String(hashBytes);
return ciphertext;
}
本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标编程语言C#.NET频道!
本文由 @小标 发布于职坐标。未经许可,禁止转载。
看完这篇文章有何感觉?已经有0人表态,0%的人喜欢
快给朋友分享吧~
评论(0)