Last active
December 7, 2019 20:46
-
-
Save muratbaseren/ab2a1e6e43773cf47677193f0d46e389 to your computer and use it in GitHub Desktop.
MyHttpClientHelper class for api requests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// MyHttpClientHelper Class.. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Configuration; | |
using System.Net; | |
using System.Net.Http; | |
using System.Net.Http.Headers; | |
using My.MVC.Data.Model; | |
namespace My.Common.Helpers | |
{ | |
public class HttpClientHelper : IDisposable | |
{ | |
public bool HasApiException { get; set; } | |
public ApiException ApiException { get; set; } | |
private readonly string _serviceUrl; | |
// <!--<add key = "WebService" value="http://hostaddress:port/api/" />--> | |
public HttpClientHelper() : this(ConfigurationManager.AppSettings["WebService"]) | |
{ | |
} | |
public HttpClientHelper(string serviceUrl) | |
{ | |
_serviceUrl = serviceUrl; | |
} | |
public TResult GetAsync<TResult>(string action, string token) | |
{ | |
TResult t = default(TResult); | |
HasApiException = false; | |
HttpResponseMessage responseMessage = GetResponse(action, token); | |
if (typeof(TResult).IsAssignableFrom(typeof(HttpResponseMessage))) //Eğer HttpResponseMessage isteniyorsa geri dönüş olarak bu değer verilir. | |
{ | |
return (TResult)Convert.ChangeType(responseMessage, typeof(TResult)); | |
} | |
if (responseMessage.IsSuccessStatusCode) | |
{ | |
t = responseMessage.Content.ReadAsAsync<TResult>().Result; | |
} | |
else | |
{ | |
SetError(responseMessage, action); | |
} | |
return t; | |
} | |
public string GetAsyncString(string action, string token) | |
{ | |
string result = null; | |
HasApiException = false; | |
HttpResponseMessage responseMessage = GetResponse(action, token); | |
if (responseMessage.IsSuccessStatusCode) | |
{ | |
result = responseMessage.Content.ReadAsStringAsync().Result; | |
} | |
else | |
{ | |
SetError(responseMessage, action); | |
} | |
return result; | |
} | |
public TResult PostAsync<TResult>(string action, HttpContent value, string token = "") | |
{ | |
TResult t = default(TResult); | |
HasApiException = false; | |
using (HttpClient client = GetHttpClient(token)) | |
{ | |
client.DefaultRequestHeaders.Accept.Clear(); | |
HttpResponseMessage responseMessage = client.PostAsync(action, value).Result; | |
if (typeof(TResult).IsAssignableFrom(typeof(HttpResponseMessage))) //Eğer HttpResponseMessage isteniyorsa geri dönüş olarak bu değer verilir. | |
{ | |
return (TResult)Convert.ChangeType(responseMessage, typeof(TResult)); | |
} | |
if (responseMessage.IsSuccessStatusCode) | |
{ | |
t = responseMessage.Content.ReadAsAsync<TResult>().Result; | |
} | |
else | |
{ | |
SetError(responseMessage, action); | |
} | |
} | |
return t; | |
} | |
public TResult PostAsJsonAsync<TResult, TValue>(string action, string token, TValue value = default(TValue)) | |
{ | |
TResult t = default(TResult); | |
HasApiException = false; | |
using (HttpClient client = GetHttpClient(token)) | |
{ | |
HttpResponseMessage responseMessage = client.PostAsJsonAsync(action, value).Result; | |
if (typeof(TResult).IsAssignableFrom(typeof(HttpResponseMessage))) //Eğer HttpResponseMessage isteniyorsa geri dönüş olarak bu değer verilir. | |
{ | |
return (TResult)Convert.ChangeType(responseMessage, typeof(TResult)); | |
} | |
if (responseMessage.IsSuccessStatusCode) | |
{ | |
t = responseMessage.Content.ReadAsAsync<TResult>().Result; | |
} | |
else | |
{ | |
SetError(responseMessage, action); | |
} | |
} | |
return t; | |
} | |
private HttpResponseMessage GetResponse(string action, string token) | |
{ | |
HttpResponseMessage responseGetChanges; | |
using (HttpClient client = GetHttpClient(token)) | |
{ | |
responseGetChanges = client.GetAsync(action).Result; | |
} | |
return responseGetChanges; | |
} | |
private HttpClient GetHttpClient(string token = "") | |
{ | |
HttpClient client = new HttpClient { BaseAddress = new Uri(_serviceUrl) }; | |
client.DefaultRequestHeaders.Accept.Clear(); | |
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); | |
client.DefaultRequestHeaders.AcceptLanguage.Add(new StringWithQualityHeaderValue("tr-TR")); | |
if (!string.IsNullOrEmpty(token)) | |
{ | |
client.DefaultRequestHeaders.Add("Authorization", token); | |
} | |
return client; | |
} | |
private void SetError(HttpResponseMessage responseMessage, string action) | |
{ | |
HasApiException = true; | |
string message = responseMessage.Content.ReadAsStringAsync().Result; | |
try | |
{ | |
if (message.Contains("exceptionMessage")) | |
{ | |
ApiException = responseMessage.Content.ReadAsAsync<ApiExceptionModel>().Result; | |
} | |
else if (message.Contains("message")) | |
{ | |
ApiException = responseMessage.Content.ReadAsAsync<ApiMessageModel>().Result; | |
} | |
else | |
{ | |
ApiException = responseMessage.Content.ReadAsAsync<ApiErrorModel>().Result; | |
} | |
ApiException.StatusCode = responseMessage.StatusCode; | |
ApiException.ReasonPharse = responseMessage.ReasonPhrase; | |
} | |
catch | |
{ | |
ApiException = new ApiErrorModel { StatusCode = HttpStatusCode.BadRequest, error = "Bilinmiyen bir hata oluştu", error_description = action + " " + responseMessage.ReasonPhrase }; | |
} | |
} | |
public void Dispose() | |
{ | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Text; | |
namespace My.MVC.Data.Model | |
{ | |
public class ApiErrorModel: ApiException | |
{ | |
public string error { get; set; } | |
public string error_description { get; set; } | |
public override string ExceptionMessage() | |
{ | |
return error_description; | |
} | |
public override string ToString() | |
{ | |
StringBuilder sb = new StringBuilder(); | |
sb.AppendLine("Exception type: " + error); | |
sb.AppendLine("Message : " + error_description); | |
return sb.ToString(); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Text; | |
namespace My.MVC.Data.Model | |
{ | |
public class ApiMessageModel : ApiException | |
{ | |
public string message { get; set; } | |
public string messageDetail { get; set; } | |
public override string ExceptionMessage() | |
{ | |
return message; | |
} | |
public override string ToString() | |
{ | |
StringBuilder sb = new StringBuilder(); | |
sb.AppendLine("Message : " + message); | |
sb.AppendLine("Message Detail: " + messageDetail); | |
return sb.ToString(); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Text; | |
namespace My.MVC.Data.Model | |
{ | |
public class ApiExceptionModel: ApiException | |
{ | |
public string message { get; set; } | |
public string exceptionMessage { get; set; } | |
public string exceptionType { get; set; } | |
public string stackTrace { get; set; } | |
public ApiExceptionModel innerException { get; set; } | |
public override string ToString() | |
{ | |
ApiExceptionModel e = this; | |
StringBuilder sb = new StringBuilder(); | |
while (e != null) | |
{ | |
sb.AppendLine("Exception type: " + e.exceptionType); | |
sb.AppendLine("Message : " + e.message); | |
sb.AppendLine("Exception Message : " + e.exceptionMessage); | |
sb.AppendLine("Stacktrace:"); | |
sb.AppendLine(e.stackTrace); | |
sb.AppendLine(); | |
e = e.innerException; | |
} | |
return sb.ToString(); | |
} | |
public override string ExceptionMessage() | |
{ | |
ApiExceptionModel e = this; | |
while (e.innerException != null) | |
{ | |
e = e.innerException; | |
} | |
return "Exception Message : " + e.exceptionMessage; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Net; | |
namespace My.MVC.Data.Model { | |
public abstract class ApiException { | |
public HttpStatusCode StatusCode { get; set; } | |
public string ReasonPharse { get; set; } | |
public abstract string ExceptionMessage(); | |
public new abstract string ToString(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This is MVC Controller | |
public class EmployeesController : BaseController | |
{ | |
[HttpPost] | |
public ActionResult Save(EmployeeView model) | |
{ | |
try | |
{ | |
model.CreatedOn = DateTime.Now; | |
model.CreatedBy = CurrentUser.UserID; | |
CurrentHttpClientHelper.PostAsJsonAsync<bool, EmployeeView>("Employees/Save", CurrentUser.Token.ToString(), model); | |
if (!CurrentHttpClientHelper.HasApiException) | |
{ | |
return Json(new | |
{ | |
Type = ResponseType.AlertFunction, | |
Title = "Bilgi", | |
Message = "Girmiş olduğunuz kayıt başarılı bir şekilde kaydedilmiştir.", | |
Function = "UpdateAction();" | |
}); | |
} | |
return Json(new | |
{ | |
Type = ResponseType.Alert, | |
Title = "Hata", | |
Message = "Sonuç eklenirken hata ile karşılaşıldı. Detaylar: <br/> " + CurrentHttpClientHelper.ApiException.ExceptionMessage() | |
}); | |
} | |
catch (Exception ex) | |
{ | |
return Json(new { Type = ResponseType.Alert, Title = "Hata", Message = "Sonuç eklenirken hata ile karşılaşıldı. Detaylar: <br/> " + ex.Message }); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This is api controller.. | |
[RoutePrefix("api/InboundCalls")] | |
public class EmployeesController : ApiController | |
{ | |
[ResponseType(typeof(bool))] | |
[Route("Save")] | |
[MyApiAuthorize] | |
[HttpPost] | |
public IHttpActionResult Save([FromBody]EmployeeView employee) | |
{ | |
EmployeeRepository employeeRepository = new EmployeeRepository(); | |
employeeRepository.MarkForInsertion(new Employee | |
{ | |
CalledDatetime = employee.CalledDatetime, | |
CreatedBy = employee.CreatedBy, | |
CreatedOn = employee.CreatedOn, | |
Description = employee.Description, | |
NameSurname = employee.NameSurname, | |
Phone = employee.Phone | |
}); | |
return Ok(employeeRepository.SaveChanges() > 0); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
using System.Linq; | |
using System.Net; | |
using System.Web.Mvc; | |
using System.Configuration; | |
namespace My.DesktopDesk.Web.Controllers { | |
[AjaxAuthorize] | |
[MySession(SessionName = "LoggedUser", RedirectUrl = "Redirect/SetUser")] | |
public class BaseController : Controller { | |
[HttpGet] | |
public ActionResult LogOff() { | |
Session.Abandon(); | |
return Redirect(ConfigurationManager.AppSettings["LoginUI"] + "Account/LogOff"); | |
} | |
public User CurrentUser | |
{ | |
get | |
{ | |
return (User)Session["LoggedUser"]; | |
} | |
} | |
//protected override void OnActionExecuting(ActionExecutingContext filterContext) | |
//{ | |
// if (LoginService != null && LoginService.SiteId != null) | |
// { | |
// base.OnActionExecuting(filterContext); | |
// } | |
// else | |
// { | |
// filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new | |
// { | |
// controller = "Redirect", | |
// action = "SetUser" | |
// })); | |
// } | |
//} | |
private HttpClientHelper _httpClientHelper; | |
public HttpClientHelper CurrentHttpClientHelper | |
{ | |
get | |
{ | |
if (_httpClientHelper == null) { | |
_httpClientHelper = new HttpClientHelper(); | |
} | |
return _httpClientHelper; | |
} | |
} | |
public ActionResult GetJSON(string url) { | |
ActionResult result = Json(CurrentHttpClientHelper.GetAsyncString(url, CurrentUser.Token.ToString()), JsonRequestBehavior.AllowGet); | |
((JsonResult)result).ContentType = "application/json"; | |
if (CurrentHttpClientHelper.HasApiException) { | |
Response.StatusCode = (int)HttpStatusCode.InternalServerError; | |
return | |
Json( | |
new { | |
Title = "Hata", | |
Message = CurrentHttpClientHelper.ApiException.ExceptionMessage() | |
}, | |
JsonRequestBehavior.AllowGet); | |
} | |
return result; | |
} | |
/* | |
private IEnumerable<ListView> GetProjectCategories() { | |
if (LoginService != null && LoginService.SiteId != null) { | |
string url = "ProjectCategory/GetCategories/" + LoginService.SiteId; | |
return CurrentHttpClientHelper.GetAsync<IEnumerable<ListView>>(url, CurrentUser.Token.ToString()); | |
} | |
return null; | |
} | |
private IEnumerable<ListView> GetProjectSubCategories(short categoryId) { | |
string url = "ProjectSubCategory/GetSubCategoryByCategory/" + categoryId; | |
return CurrentHttpClientHelper.GetAsync<IEnumerable<ListView>>(url, CurrentUser.Token.ToString()); | |
} | |
public ActionResult GetCategories(byte id) { | |
var categories = ProjectCategories.Where(p => p.ParentId == id).Select(p => new SelectListItem { | |
Text = p.Name, | |
Value = p.Id.ToString() | |
}); | |
return Json(categories.ToList(), JsonRequestBehavior.AllowGet); | |
} | |
public ActionResult GetSubCategories(short id) { | |
var categories = GetProjectSubCategories(id).Select(p => new SelectListItem { | |
Text = p.Name, | |
Value = p.Id.ToString() | |
}); | |
return Json(categories.ToList(), JsonRequestBehavior.AllowGet); | |
} | |
public IEnumerable<ListView> ProjectCategories | |
{ | |
get | |
{ | |
return GetProjectCategories(); | |
} | |
} | |
*/ | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Web.Hosting; | |
using System.Web.Mvc; | |
using Marm.MVC.Data.Model; | |
using Marm.MVC.Enums; | |
using System.Linq; | |
using System.Configuration; | |
using Marm.Common.Extension; | |
namespace Marm.MVC.Attribute { | |
/// <summary> | |
/// Session düştüğünde yeniden tokendan user oluşmasını sağlar | |
/// </summary> | |
public class MySessionAttribute : ActionFilterAttribute { | |
public string SessionName { get; set; } | |
public string RedirectUrl { get; set; } | |
public LoginAuthority Authority { get; set; } | |
public MarmSessionAttribute() { | |
SessionName = "LoggedUser"; | |
RedirectUrl = "redirect/setuser"; | |
Authority = LoginAuthority.Default; | |
} | |
public override void OnActionExecuting(ActionExecutingContext filterContext) { | |
User user = (User)filterContext.HttpContext.Session[SessionName]; | |
var appId =ConfigurationManager.AppSettings["AppId"]; | |
var currentService = appId != null && user != null && user.Services != null ? user.Services.FirstOrDefault(p=> p.AppId == appId.ToByte()) : null; | |
if ((user == null || (Authority != LoginAuthority.Default && (currentService == null || currentService.Authority != Authority))) && !filterContext.HttpContext.Response.IsRequestBeingRedirected) { | |
string urlRoot = filterContext.HttpContext.Request.Url.AbsoluteUri.Replace(filterContext.HttpContext.Request.Url.PathAndQuery, "/"); | |
string query = filterContext.HttpContext.Request.Url.Query + (filterContext.HttpContext.Request.Url.Query.Length > 0 ? "&": "?") + "returnUrl=" + filterContext.HttpContext.Server.UrlEncode(filterContext.HttpContext.Request.Url.AbsoluteUri); | |
filterContext.Result = new RedirectResult((HostingEnvironment.ApplicationVirtualPath.Length > 1 ? HostingEnvironment.ApplicationVirtualPath : urlRoot) + "/" + RedirectUrl + query); | |
} else { | |
base.OnActionExecuting(filterContext); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment