Files
OSS.Tools/OSS.Http.Extention/OsRestExtention.cs
T
2017-05-25 17:33:40 +08:00

67 lines
2.3 KiB
C#
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#region Copyright (C) 2016 Kevin (OSS开源系列) 公众号:osscoder
/***************************************************************************
*   文件功能描述:OSS.Http.Extention - 通用请求结果扩展
*
*   创建人: Kevin
* 创建人Email:1985088337@qq.com
* 创建时间: 2017-5-25
*
*****************************************************************************/
#endregion
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
using OSS.Common.ComModels;
using OSS.Common.ComModels.Enums;
using OSS.Common.Modules;
using OSS.Common.Plugs.LogPlug;
using OSS.Http.Mos;
namespace OSS.Http.Extention
{
/// <summary>
/// 通用请求结果扩展
/// </summary>
public static class OsRestExtention
{
/// <summary>
/// 处理远程请求方法,并返回需要的实体
/// </summary>
/// <typeparam name="T">需要返回的实体类型</typeparam>
/// <param name="request">远程请求组件的request基本信息</param>
/// <param name="funcFormat">获取实体格式化方法</param>
/// <param name="moduleName">模块名称</param>
/// <returns>实体类型</returns>
public static async Task<T> RestCommon<T>(this OsHttpRequest request,
Func<HttpResponseMessage, Task<T>> funcFormat = null,string moduleName=ModuleNames.Default)
where T : ResultMo, new()
{
T t = default(T);
try
{
var resp = await request.RestSend();
if (resp.IsSuccessStatusCode)
{
if (funcFormat != null)
t = await funcFormat(resp);
else
{
var contentStr = await resp.Content.ReadAsStringAsync();
t = JsonConvert.DeserializeObject<T>(contentStr);
}
}
}
catch (Exception ex)
{
t = new T() { Ret = (int)ResultTypes.InnerError, Message = ex.Message };
LogUtil.Error(string.Concat("基类请求出错,错误信息:", ex.Message), "RestCommon",moduleName);
}
return t ?? new T() { Ret = 0 };
}
}
}