public static void Register(HttpConfiguration config) { EnableCorsAttribute CorsAttribute = new EnableCorsAttribute("*", "*", "*", "X-Pagination,x-filename"); config.EnableCors(CorsAttribute); // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); // Uncomment the following line of code to enable query support for actions with an IQueryable or IQueryable<T> return type. // To avoid processing unexpected or malicious queries, use the validation settings on QueryableAttribute to validate incoming queries. // For more information, visit http://go.microsoft.com/fwlink/?LinkId=279712. //config.EnableQuerySupport(); // To disable tracing in your application, please comment out or remove the following line of code // For more information, refer to: http://www.asp.net/web-api config.EnableSystemDiagnosticsTracing(); config.Filters.Add(new ErrorHandleAttribute("错误处理")); var jsonFormatter = new System.Net.Http.Formatting.JsonMediaTypeFormatter(); jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); config.Formatters.Clear(); config.Formatters.Add(jsonFormatter); config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; }
//Send application instance heartbeat //PUT /eureka/v2/apps/appID/instanceID //HTTP Code: // * 200 on success // * 404 if instanceID doesn’t exist public async Task <bool> SendHeartbeat(DataCenterMetadata dcData) { string url = this.EurekaServiceRoot + "/" + dcData.InstanceId; try { HttpClient client = this.httpClientFactory.CreateInstance(); System.Net.Http.Formatting.MediaTypeFormatter frm = new System.Net.Http.Formatting.JsonMediaTypeFormatter(); HttpResponseMessage response = await client.PutAsync(url, "", frm, "application/json"); //response.EnsureSuccessStatusCode(); if (response.StatusCode != System.Net.HttpStatusCode.OK) { string tmp = await response.Content.ReadAsStringAsync(); Trace.TraceError("Error on Heartbeat: " + tmp); return(false); } else if (response.StatusCode == System.Net.HttpStatusCode.NotFound) { Trace.TraceWarning("Heartbeat failed. Instance does not exist."); return(false); } else { Trace.TraceInformation("Heartbeat has been successfully submitted."); } } catch (Exception ex) { throw ex; } return(true); }
public static void Register(HttpConfiguration config) { // Web API 配置和服务 // Web API 路由 config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); //权限过滤 config.MessageHandlers.Add(new AuthenticationHandler()); //通用错误处理过滤器,保证错误信息都是以{HasError:1,ErrorMessage:""}的格式 config.Filters.Add(new GeneralExceptionFilterAttribute()); //转换POST传递过来的参数值 config.ParameterBindingRules.Insert(0, SimplePostVariableParameterBinding.HookupParameterBinding); #region 格式化json日期 System.Net.Http.Formatting.JsonMediaTypeFormatter jsonFormatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter; jsonFormatter.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; jsonFormatter.SerializerSettings.ContractResolver = new CancelNullResolver(); //取消json空值 jsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; //树结构无法格式化的问题 #endregion //让所有的接口都支持跨域(NuGet搜索microsoft.aspnet.webapi.cors) GlobalConfiguration.Configuration.EnableCors(new EnableCorsAttribute("*", "*", "*")); }
public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log) { //Parse query parameter string id = req.GetQueryNameValuePairs() .FirstOrDefault(q => string.Compare(q.Key, "id", true) == 0) .Value; Guid idGuid; if (!Guid.TryParse(id, out idGuid)) { return(req.CreateResponse(HttpStatusCode.BadRequest, "Id is not a valid")); } string resultJson = null; try { //TODO: Implement IOC var customerDataFactory = new ShelteredDepthsDataFactory(new ShelteredDepthsApi()); var customerService = new CustomerService(customerDataFactory); resultJson = customerService.GetCustomer(idGuid); } catch (Exception e) { log.Error("GetCustomer failed", e); return(req.CreateResponse(HttpStatusCode.BadRequest, $"An error has occured: {e}")); } var jsonFormatter = new System.Net.Http.Formatting.JsonMediaTypeFormatter(); return(resultJson == null ? req.CreateResponse(HttpStatusCode.BadRequest, "Empty Data") : req.CreateResponse(HttpStatusCode.OK, resultJson, jsonFormatter, new MediaTypeWithQualityHeaderValue("application/json"))); }
//Put instance back into service //PUT /eureka/v2/apps/appID/instanceID/status?value=UP //HTTP Code: // * 200 on success // * 500 on failure public async Task <bool> PutInstanceToService(DataCenterMetadata dcData) { string url = this.EurekaServiceRoot + "/" + dcData.InstanceId + "/status?value=UP"; try { HttpClient client = this.httpClientFactory.CreateInstance(); System.Net.Http.Formatting.MediaTypeFormatter frm = new System.Net.Http.Formatting.JsonMediaTypeFormatter(); HttpResponseMessage response = await client.PutAsync(url, "", frm, "application/json"); if (response.StatusCode != System.Net.HttpStatusCode.OK) { string tmp = await response.Content.ReadAsStringAsync(); Trace.TraceError("Error on TakeInstanceDown: " + tmp); return(false); } else { Trace.TraceInformation("TakeInstanceDown has been successfully submitted."); } } catch (Exception ex) { throw ex; } return(true); }
// This code configures Web API. The Startup class is specified as a type // parameter in the WebApp.Start method. public void Configuration(IAppBuilder appBuilder) { // Configure Web API for self-host. HttpConfiguration config = new HttpConfiguration(); config.MapHttpAttributeRoutes(); config.Formatters.Clear(); var jsonFormatter = new System.Net.Http.Formatting.JsonMediaTypeFormatter(); jsonFormatter.UseDataContractJsonSerializer = false; // defaults to false, but no harm done jsonFormatter.SerializerSettings.DateFormatHandling = DateFormatHandling.IsoDateFormat; jsonFormatter.SerializerSettings.Formatting = Formatting.Indented; jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); config.Formatters.Add(jsonFormatter); appBuilder.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); appBuilder.UseWebApi(config); }
public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log) { string resultJson = null; try { //Parse page parameter and default to 0 string pageString = req.GetQueryNameValuePairs() .FirstOrDefault(q => string.Compare(q.Key, "page", true) == 0) .Value; int page; int.TryParse(pageString, out page); //TODO: Implement IOC var customerDataFactory = new ShelteredDepthsDataFactory(new ShelteredDepthsApi()); var customerService = new CustomerService(customerDataFactory); resultJson = customerService.GetCustomers(page); } catch (Exception e) { log.Error("GetAll failed", e); return(req.CreateResponse(HttpStatusCode.BadRequest, $"An error has occured {e.Message}")); } var jsonFormatter = new System.Net.Http.Formatting.JsonMediaTypeFormatter(); return(resultJson == null ? req.CreateResponse(HttpStatusCode.BadRequest, "No data found") : req.CreateResponse(HttpStatusCode.OK, resultJson, jsonFormatter, new MediaTypeWithQualityHeaderValue("application/json"))); }
private HttpResponseMessage Execute() { HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Unauthorized); System.Net.Http.Formatting.MediaTypeFormatter jsonFormatter = new System.Net.Http.Formatting.JsonMediaTypeFormatter(); response.Content = new System.Net.Http.ObjectContent <object>(ResponseMessage, jsonFormatter); response.RequestMessage = Request; response.ReasonPhrase = ReasonPhrase; return(response); }
public void Configuration(IAppBuilder app) { var builder = new ContainerBuilder(); builder.RegisterModule <WebApiModule>(); var config = new HttpConfiguration(); builder.RegisterApiControllers(Assembly.GetExecutingAssembly()) .PropertiesAutowired(); var container = builder.Build(); var sampleDependencyResolver = new AutofacWebApiDependencyResolver(container); app.UseAutofacMiddleware(container); app.UseAutofacWebApi(config); var culture = new CultureInfo("en-US") { DateTimeFormat = { ShortDatePattern = "MM/dd/yyyy", LongTimePattern = "" } }; CultureInfo.DefaultThreadCurrentCulture = culture; CultureInfo.DefaultThreadCurrentUICulture = culture; config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); config.Formatters.Remove(config.Formatters.XmlFormatter); var formatter = new System.Net.Http.Formatting.JsonMediaTypeFormatter(); config.Formatters.Add(formatter); config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver(); var clientFolder = ConfigurationManager.AppSettings["ClientFolder"]; app.MapWhen(context => { return(true); }, trueApp => { var fileServerOptions = new FileServerOptions() { RequestPath = PathString.Empty, FileSystem = new PhysicalFileSystem(@".\" + clientFolder), }; trueApp.UseFileServer(fileServerOptions); trueApp.UseWebApi(config); }); }
public CreateTests(EditionFixture fixture, ITestOutputHelper output) { _fixture = fixture .ConfigureOutput(output) as EditionFixture ?? throw new ArgumentNullException(nameof(fixture)); var formatter = new System.Net.Http.Formatting.JsonMediaTypeFormatter(); formatter.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("application/problem+json")); _defaultFormatters = new[] { formatter }; }
public static void Configure(HttpConfiguration config) { JsonMediaTypeFormatter formatter = config.Formatters.OfType <JsonMediaTypeFormatter>().First(); formatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); formatter.SerializerSettings.DateFormatHandling = DateFormatHandling.IsoDateFormat; formatter.SerializerSettings.Formatting = Formatting.Indented; formatter.SerializerSettings.Converters.Add(new GuidConverter()); formatter.SerializerSettings.Converters.Add(new StringEnumConverter { CamelCaseText = true }); config.MapHttpAttributeRoutes(); }
public async Task <FinalizarProjetoResultado> FinalizarProjeto() { Glass.Api.Projeto.Projeto projeto = null; var tempFolder = System.IO.Path.Combine(System.IO.Path.GetTempPath()); var multipartProvider = new MultipartFormDataStreamProvider(tempFolder); // Realiza a leitura as partes postadas await Request.Content.ReadAsMultipartAsync(multipartProvider); await multipartProvider.ExecutePostProcessingAsync(); foreach (var content in multipartProvider.Contents) { var headers = content.Headers; var name = headers.ContentDisposition.Name; if (name == "\"projeto\"") { using (var stream = await content.ReadAsStreamAsync()) { var formatter = new System.Net.Http.Formatting.JsonMediaTypeFormatter(); projeto = (Glass.Api.Projeto.Projeto)(await formatter.ReadFromStreamAsync(typeof(Glass.Api.Projeto.Projeto), stream, null, null)); } break; } } // Recupera a relação das imagens postadas var imagens = multipartProvider.FileData .Select(fileData => { var nome = fileData.Headers.ContentDisposition.Name?.TrimStart('"')?.TrimEnd('"'); return(new ImagemProjeto(nome, null, fileData.LocalFileName)); }) .Where(f => f.Nome.StartsWith("img")) .OrderBy(f => f.Nome); //provider.Contents.Where(f => f.n) try { PedidoDAO.Instance.FinalizarProjetoGerarPedidoApp(projeto, imagens); return(new FinalizarProjetoResultado(true, null)); } catch (Exception x) { return(new FinalizarProjetoResultado(false, x.Message.GetFormatter())); } }
public async Task <JObject> ApiPostAsync(string url, string token, string api, string[] fields, int version, Dictionary <string, string> optionalParameters, string html, string contentType) { #region Argument Validation if (string.IsNullOrWhiteSpace(url)) { throw new ArgumentNullException("url"); } if (string.IsNullOrWhiteSpace(token)) { throw new ArgumentNullException("token"); } if (string.IsNullOrWhiteSpace(api)) { throw new ArgumentNullException("api"); } if (string.IsNullOrWhiteSpace(html)) { throw new ArgumentNullException("html"); } if (string.IsNullOrWhiteSpace(contentType)) { throw new ArgumentNullException("contentType"); } // TODO: Validate this is a valid check if (version < 2) { throw new ArgumentException("Invalid api version"); } #endregion StringBuilder apiUrl = CreateUrl(url, token, api, fields, version, optionalParameters, false); var formatter = new System.Net.Http.Formatting.JsonMediaTypeFormatter(); var result = await httpClient.PostAsync <string>(apiUrl.ToString(), html, formatter); if (result.IsSuccessStatusCode) { return(JObject.Parse(await result.Content.ReadAsStringAsync())); } else { throw new HttpRequestException(result.ReasonPhrase); } }
public void Configuration(IAppBuilder app) { var builder = new ContainerBuilder(); builder.RegisterModule<WebApiModule>(); var config = new HttpConfiguration(); builder.RegisterApiControllers(Assembly.GetExecutingAssembly()) .PropertiesAutowired(); var container = builder.Build(); var sampleDependencyResolver = new AutofacWebApiDependencyResolver(container); app.UseAutofacMiddleware(container); app.UseAutofacWebApi(config); var culture = new CultureInfo("en-US") { DateTimeFormat = { ShortDatePattern = "MM/dd/yyyy", LongTimePattern = "" } }; CultureInfo.DefaultThreadCurrentCulture = culture; CultureInfo.DefaultThreadCurrentUICulture = culture; config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); config.Formatters.Remove(config.Formatters.XmlFormatter); var formatter = new System.Net.Http.Formatting.JsonMediaTypeFormatter(); config.Formatters.Add(formatter); config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver(); var clientFolder = ConfigurationManager.AppSettings["ClientFolder"]; app.MapWhen(context => { return true; }, trueApp => { var fileServerOptions = new FileServerOptions() { RequestPath = PathString.Empty, FileSystem = new PhysicalFileSystem(@".\" + clientFolder), }; trueApp.UseFileServer(fileServerOptions); trueApp.UseWebApi(config); }); }
public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional }); // camelCase by default System.Net.Http.Formatting.JsonMediaTypeFormatter formatter = config.Formatters.JsonFormatter; formatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); config.Filters.Add(new UnhandledExceptionFilter()); config.Formatters.Add(new ICalFormatter()); config.MessageHandlers.Add(new OutlookAgentMessageHandler()); }
public static void Register(HttpConfiguration config) { // Web API 配置和服务 // Web API 路由 config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "InvoiceImplementation/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); var jsonFormatter = new System.Net.Http.Formatting.JsonMediaTypeFormatter(); config.Services.Replace(typeof(System.Net.Http.Formatting.IContentNegotiator), new JsonContentNegotiator(jsonFormatter)); }
public static void Register(HttpConfiguration config) { // Configuración y servicios de API web // Rutas de API web config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); System.Net.Http.Formatting.JsonMediaTypeFormatter json = GlobalConfiguration.Configuration.Formatters.JsonFormatter; config.EnableCors(new AccessPolicyCors()); }
public static void Register(HttpConfiguration config) { // Web API configuration and services // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}",//让webapi根据action来选择相应的方法,而不是采用webapi自带的由HttpMethod defaults: new { id = RouteParameter.Optional } ); //权限过滤 config.MessageHandlers.Add(new AuthenticationHandler()); //通用错误处理过滤器,保证错误信息都是以{HasError:1,ErrorMessage:""}的格式 config.Filters.Add(new GeneralExceptionFilterAttribute()); //转换POST传递过来的参数值 config.ParameterBindingRules.Insert(0, SimplePostVariableParameterBinding.HookupParameterBinding); #region 格式化json日期 System.Net.Http.Formatting.JsonMediaTypeFormatter jsonFormatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter; jsonFormatter.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; jsonFormatter.SerializerSettings.ContractResolver = new CancelNullResolver(); //取消json空值 jsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; //树结构无法格式化的问题 #endregion ////解决RestSharp请求https匿名证书 //ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true; //让所有的接口都支持跨域 GlobalConfiguration.Configuration.EnableCors(new EnableCorsAttribute("*", "*", "*")); #region Ioc Autofac var builder = new ContainerBuilder(); builder.RegisterAssemblyTypes(Assembly.Load(ConfigurationSettings.AppSettings["LoadAssembly"])) .Where(t => true) .AsImplementedInterfaces(); builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); var container = builder.Build(); GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container); GlobalConfiguration.Configuration.EnsureInitialized(); #endregion #region 系统日志 log4net.Config.XmlConfigurator.Configure(new System.IO.FileInfo(System.Web.HttpContext.Current.Server.MapPath("~") + @"\log4net.config")); #endregion }
//[Route("api/JSearch/GetJobs")] public HttpResponseMessage GetJobbySearch([FromUri] String PLocation, [FromUri] String PKeySkill, [FromUri] String PQualification, [FromUri] String PJobCategory, [FromUri] String PMinExp, [FromUri] String PMaxExp, [FromUri] String PJobCode, [FromUri] String PSourceType) { #region R&D Work //{Location:"CTYGSP0510000001",KeySkill:"accounts",Qualification:"%",JobCategory:"%",MinExp:"0",MaxExp:"31",JobCode:"%",SourceType:"PERM"} //dynamic item1 = Newtonsoft.Json.JsonConvert.DeserializeObject(Params); //var lst = Newtonsoft.Json.JsonConvert.DeserializeObject(Params); //List<dynamic> lstitem = new List<dynamic>(); //lstitem.Add(item1); ////var bb = from item in lst select item; ////foreach(var aa in lst) ////{ ////} #endregion R&D Work JSParams JParam = new JSParams() { Location = PLocation, KeySkill = PKeySkill, Qualification = PQualification, JobCategory = PJobCategory, MinExp = PMinExp, MaxExp = PMaxExp, JobCode = PJobCode, SourceType = PSourceType }; List <dynamic> lstJob = GetParamDetails(JParam); ResponseClass objresponse = new ResponseClass() { ResponseCode = lstJob.Count > 0 ? 001 : -101, ResponseData = lstJob, ResponseStatus = lstJob.Count > 0 ? "Success" : "Failed" }; var jsonformat = new System.Net.Http.Formatting.JsonMediaTypeFormatter(); HttpResponseMessage response = new HttpResponseMessage(); response.Content = new ObjectContent(objresponse.GetType(), objresponse, jsonformat); response.StatusCode = lstJob.Count > 0 ? HttpStatusCode.OK : HttpStatusCode.NotFound; return(response); }
//Register new application instance //POST /eureka/v2/apps/appID //Input: JSON/XML payload HTTP Code: 204 on success public async Task <bool> Register(DataCenterMetadata dcData) { EurekaRegistrationInfo instanceData = new EurekaRegistrationInfo(); instanceData.Instance.DataCenterInfo.Name = dcData.DataCenterName; instanceData.Instance.DataCenterInfo.Metadata = dcData; instanceData.Instance.HostName = dcData.HostName;// "ec2-50-16-138-165.compute-1.amazonaws.com"; instanceData.Instance.App = this.ApplicationName; instanceData.Instance.Port = this.ApplicationPort; instanceData.Instance.IPAddr = dcData.LocalIPv4; instanceData.Instance.VipAddress = dcData.PublicIPv4;// "50.16.138.165"; instanceData.Instance.SecurePort = this.ApplicationSecurePort; if (this.ApplicationSecurePort > 0) { instanceData.Instance.SecureVipAddress = dcData.PublicIPv4; } HttpClient client = null; string url = this.EurekaServiceRoot; try { System.Net.Http.Formatting.MediaTypeFormatter frm = new System.Net.Http.Formatting.JsonMediaTypeFormatter(); client = this.httpClientFactory.CreateInstance(); HttpResponseMessage response = await client.PostAsync(url, instanceData, frm, "application/json"); //response.EnsureSuccessStatusCode(); if (response.StatusCode != System.Net.HttpStatusCode.NoContent) { string tmp = await response.Content.ReadAsStringAsync(); Trace.TraceError("Error on Register: " + tmp); return(false); } else { Trace.TraceInformation("Registration completed. Status: " + response.StatusCode.ToString()); } } catch (Exception ex) { throw ex; } return(true); }
public HttpResponseMessage Get() { String Version = System.Configuration.ConfigurationManager.AppSettings["APKVersion"].ToString(); ResponseClass objresponse = new ResponseClass() { ResponseCode = 001, ResponseData = Version, ResponseStatus = "Success" }; var jsonformat = new System.Net.Http.Formatting.JsonMediaTypeFormatter(); HttpResponseMessage response = new HttpResponseMessage(); response.Content = new ObjectContent(objresponse.GetType(), objresponse, jsonformat); response.StatusCode = HttpStatusCode.OK; return(response); }
//[Route("api/Param/GetCountryBySearch")] public HttpResponseMessage GetCountryBySearch([FromUri] string SearchName, [FromUri] String SearchVal) { List <dynamic> lstCountrySearch = GetParamDetailsBySearch(ParamType.Country, string.Empty, SearchName, SearchVal); ResponseClass objresponse = new ResponseClass() { ResponseCode = lstCountrySearch.Count > 0 ? 001 : -101, ResponseData = lstCountrySearch, ResponseStatus = lstCountrySearch.Count > 0 ? "Success" : "Failed" }; var jsonformat = new System.Net.Http.Formatting.JsonMediaTypeFormatter(); HttpResponseMessage response = new HttpResponseMessage(); response.Content = new ObjectContent(objresponse.GetType(), objresponse, jsonformat); response.StatusCode = lstCountrySearch.Count > 0 ? HttpStatusCode.OK : HttpStatusCode.NotFound; return(response); }
//[Route("api/Param/GetExperience")] public HttpResponseMessage GetAllExperience() { List <dynamic> lstJobExp = GetParamDetails(ParamType.Experience, String.Empty); ResponseClass objresponse = new ResponseClass() { ResponseCode = lstJobExp.Count > 0 ? 001 : -101, ResponseData = lstJobExp, ResponseStatus = lstJobExp.Count > 0 ? "Success" : "Failed" }; var jsonformat = new System.Net.Http.Formatting.JsonMediaTypeFormatter(); HttpResponseMessage response = new HttpResponseMessage(); response.Content = new ObjectContent(objresponse.GetType(), objresponse, jsonformat); response.StatusCode = lstJobExp.Count > 0 ? HttpStatusCode.OK : HttpStatusCode.NotFound; return(response); }
public static void Register(HttpConfiguration config) { // Web API configuration and services //To set the letters to be written in camel casse System.Net.Http.Formatting.JsonMediaTypeFormatter jsonFormatter = config.Formatters.OfType <System.Net.Http.Formatting.JsonMediaTypeFormatter>().First(); jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); }
static void Main(string[] args) { ReadFile r = new ReadFile(); string bug = r.ReadTrxFile(); var data = new Issue(); data.fields.project.key = "EM"; data.fields.summary = "Bug" + " " + DateTime.Now; data.fields.description = bug; data.fields.issuetype.name = "Bug"; // string postUrl = "http://testagent.southeastasia.cloudapp.azure.com:7000/rest/api/latest/issue"; //string postUrl = "http://devopsjira.southeastasia.cloudapp.azure.com/rest/api/latest/issue"; string postUrl = "https://mtdevopscoe.atlassian.net/rest/api/latest/issue"; System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(); client.BaseAddress = new System.Uri(postUrl); // byte[] cred = UTF8Encoding.UTF8.GetBytes("Priyanka:Ult1m@te"); // byte[] cred = UTF8Encoding.UTF8.GetBytes("Abhideep:London@123"); byte[] cred = UTF8Encoding.UTF8.GetBytes("jitendra.kumar:Welcome@123"); client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(cred)); client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); System.Net.Http.Formatting.MediaTypeFormatter jsonFormatter = new System.Net.Http.Formatting.JsonMediaTypeFormatter(); //System.Net.Http.HttpContent content = new System.Net.Http.ObjectContent<string>(data, jsonFormatter); System.Net.Http.HttpContent content = new System.Net.Http.ObjectContent <Issue>(data, jsonFormatter); System.Net.Http.HttpResponseMessage response = client.PostAsync("issue", content).Result; if (response.IsSuccessStatusCode) { string result = response.Content.ReadAsStringAsync().Result; // its will be 200 OK (inserted) Console.Write(result); } else { Console.Write(response.StatusCode.ToString()); Console.ReadLine(); } }
public ActionResult CreateExpense(Expense model) { if (ModelState.IsValid && model != null) { using (HttpClient client = new HttpClient()) { Uri uri = HttpContext.Request.Url; string host = uri.Scheme + Uri.SchemeDelimiter + uri.Host + ":" + uri.Port + "/"; MvcApplication.Logger.InfoFormat("CreateExpense host address is: {0}", host); if (!string.IsNullOrEmpty(host)) { if (!host.EndsWith("/")) host = string.Format("{0}/", host); client.BaseAddress = new Uri(host); } client.DefaultRequestHeaders.Add("UserId", string.Format("{0}", Session["UserIdValue"])); client.DefaultRequestHeaders.Add("authenticationToken", "1111"); var formatter = new System.Net.Http.Formatting.JsonMediaTypeFormatter(); using (HttpResponseMessage response = client.PostAsync<Expense>("api/Expense/Complex/", model, formatter).Result) { if (response.IsSuccessStatusCode) { ViewBag.Message = "Data has been successfully submitted"; var resp1 = response.Content.ReadAsStringAsync().Result; if (!string.IsNullOrEmpty(resp1)) ViewBag.Response = resp1; } } } return RedirectToAction("CreateExpense"); } ViewBag.Message = "Fail to submit data"; return RedirectToAction("CreateExpense"); }
public override void OnAuthentication(HttpAuthenticationContext context) { System.Net.Http.Formatting.MediaTypeFormatter jsonFormatter = new System.Net.Http.Formatting.JsonMediaTypeFormatter(); var ci = context.Principal.Identity as ClaimsIdentity; //First of all we are going to check that the request has the required Authorization header. If not set the Error var authHeader = context.Request.Headers.Authorization; //Change "Bearer" for the needed schema if (authHeader == null || authHeader.Scheme != "Bearer") { context.ErrorResult = context.ErrorResult = new AuthenticationFailureResult("unauthorized", context.Request, new { Error = new { Code = 401, Message = "Request require authorization" } }); } //If the token has expired the property "IsAuthenticated" would be False, then set the error else if (!ci.IsAuthenticated) { context.ErrorResult = new AuthenticationFailureResult("unauthorized", context.Request, new { Error = new { Code = 401, Message = "The Token has expired" } }); } }
public HttpResponseMessage GetAllIndustry() { List <dynamic> lstindustry = GetParamDetails(ParamType.IndustryCat, string.Empty); ResponseClass objresponse = new ResponseClass() { ResponseCode = lstindustry.Count > 0 ? 001 : -101, ResponseData = lstindustry, ResponseStatus = lstindustry.Count > 0 ? "Success" : "Failed" }; var jsonformat = new System.Net.Http.Formatting.JsonMediaTypeFormatter(); HttpResponseMessage response = new HttpResponseMessage(); response.Content = new ObjectContent(objresponse.GetType(), objresponse, jsonformat); response.StatusCode = lstindustry.Count > 0 ? HttpStatusCode.OK : HttpStatusCode.NotFound; //response.RequestMessage = strLoc.Length > 0 ? "Success" : "Failed"; return(response); }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); //RouteConfig.RegisterRoutes(RouteTable.Routes); var formatters = GlobalConfiguration.Configuration.Formatters; formatters.Remove(formatters.XmlFormatter); formatters.Remove(formatters.JsonFormatter); Newtonsoft.Json.JsonSerializerSettings serializeSettings = new Newtonsoft.Json.JsonSerializerSettings { NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore }; System.Net.Http.Formatting.JsonMediaTypeFormatter jsonFormatter = new System.Net.Http.Formatting.JsonMediaTypeFormatter() { Indent = false, SerializerSettings = serializeSettings }; formatters.Add(jsonFormatter); }
public HttpResponseMessage CandidateProfile([FromUri] string ResumeID) { int?ReturnStatus = 0; System.Data.DataTable dtd = new System.Data.DataTable(); DatabaseTransaction objDB = new DatabaseTransaction(); objDB.AddConnectionName = "RMSRemote"; List <KeyValuePair <object, object> > lst = new List <KeyValuePair <object, object> >(); lst.Add(new KeyValuePair <object, object>("@RMSResumeID", ResumeID)); dtd = objDB.SqlGetData("RMSProfileDetaileMobile", ref lst, ExecType.Dynamic, ReturnDBOperation.DataTable, ref ReturnStatus); var dtlist = new List <dynamic>(); if (dtd != null && dtd.Rows.Count > 0) { dtlist = new CommonMethods().DatatableToList(dtd); } ResponseClass objresponse = new ResponseClass() { ResponseCode = dtlist.Count > 0 ? 001 : -101, ResponseData = dtlist, ResponseStatus = dtlist.Count > 0 ? "Success" : "Failed" }; JavaScriptSerializer objserz = new JavaScriptSerializer(); var jsonformat = new System.Net.Http.Formatting.JsonMediaTypeFormatter(); String strz = objserz.Serialize(objresponse); HttpResponseMessage response = new HttpResponseMessage(); response.Content = new ObjectContent(objresponse.GetType(), objresponse, jsonformat); //response.Content = new ObjectContent(strz.GetType(), strz, jsonformat); response.StatusCode = dtlist.Count > 0 ? HttpStatusCode.OK : HttpStatusCode.NotFound; return(response); }
public static void Register(HttpConfiguration config) { config.EnableCors(new System.Web.Http.Cors.EnableCorsAttribute("*", "*", "*")); config.Routes.MapHttpRoute( name: "MyApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); config.Formatters.Remove(config.Formatters.XmlFormatter); config.Formatters.Remove(config.Formatters.JsonFormatter); System.Net.Http.Formatting.JsonMediaTypeFormatter myJSONFormatter = new System.Net.Http.Formatting.JsonMediaTypeFormatter(); myJSONFormatter.SerializerSettings.ContractResolver = new MyJsonContractResolver(); config.Formatters.Add(myJSONFormatter); config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; }
//[Route("api/Param/GetLocation")] public HttpResponseMessage GetAllLocation() { //[FromUri] String strParam //strParam = strParam.Length > 0 ? strParam : "CONGSP0510000001"; List <dynamic> lstLocation = GetParamDetails(ParamType.Location, "CONGSP0510000001"); ResponseClass objresponse = new ResponseClass() { ResponseCode = lstLocation.Count > 0 ? 001 : -101, ResponseData = lstLocation, ResponseStatus = lstLocation.Count > 0 ? "Success" : "Failed" }; var jsonformat = new System.Net.Http.Formatting.JsonMediaTypeFormatter(); HttpResponseMessage response = new HttpResponseMessage(); response.Content = new ObjectContent(objresponse.GetType(), objresponse, jsonformat); response.StatusCode = lstLocation.Count > 0 ? HttpStatusCode.OK : HttpStatusCode.NotFound; //response.RequestMessage = strLoc.Length > 0 ? "Success" : "Failed"; return(response); }
public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); config.Filters.Add(new ResponseFilterAttribute()); config.DependencyResolver = new NinjectDependencyResolverForWebApi(); //响应返回 application/ json config.Formatters.Clear(); var jsonFormatter = new System.Net.Http.Formatting.JsonMediaTypeFormatter(); var settings = jsonFormatter.SerializerSettings; var timeConverter = new Newtonsoft.Json.Converters.IsoDateTimeConverter(); //这里使用自定义日期格式 timeConverter.DateTimeFormat = "yyyy-MM-dd HH:mm"; settings.Converters.Add(timeConverter); config.Formatters.Add(jsonFormatter); // 返回 Json 设为大小写 Camel 驼峰形式 config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver(); }