public HttpResponseMessage Register(HttpRequestMessage request, RegistrationViewModel user) { return CreateHttpResponse(request, () => { HttpResponseMessage response = null; if (!ModelState.IsValid) { response = request.CreateResponse(HttpStatusCode.BadRequest, new {success = false}); } else { var _user = _membershipService.CreateUser(user.Username, user.Email, user.Password, new[] {1}); if (_user != null) { response = request.CreateResponse(HttpStatusCode.OK, new {success = true}); } else { response = request.CreateResponse(HttpStatusCode.OK, new {success = false}); } } return response; }); }
public HttpResponseMessage Register(HttpRequestMessage request, ClientModel _clientModel) { return CreateHttpResponse(request, () => { HttpResponseMessage response = null; if (!ModelState.IsValid) { response = request.CreateResponse(HttpStatusCode.BadRequest, ModelState.Keys.SelectMany(k => ModelState[k].Errors) .Select(m => m.ErrorMessage).ToArray()); } else { Client newClient = new Client(); newClient.AsClient(_clientModel); _clientRepository.Add(newClient); _unitOfWork.Commit(); _clientModel = Mapper.Map<Client, ClientModel>(newClient); response = request.CreateResponse<ClientModel>(HttpStatusCode.Created, _clientModel); } return response; }); }
// POST: api/Entry/URL public async Task<HttpResponseMessage> Post(HttpRequestMessage request) { string data = await request.Content.ReadAsStringAsync(); string url = string.Empty; if (!string.IsNullOrEmpty(data)) { url = HttpUtility.HtmlEncode(data.Trim()); } IValidationContext context = await _validationService.UrlValid(url); if (!context.IsValid) { StringBuilder sb = new StringBuilder(); foreach (string error in context.ErrorMessages) { sb.Append(error).Append(" "); } return request.CreateResponse(HttpStatusCode.BadRequest, sb.ToString().Trim()); } return request.CreateResponse(HttpStatusCode.Accepted, await _entryService.AddEntry(new HomeModel() { Url = HttpUtility.HtmlEncode(url), Host = request.RequestUri.Host })); }
public User GetUser(HttpRequestMessage request, string userId, string sessionKey) { var users = MongoDBHelper.database.GetCollection<User>("users"); var user = users.FindOne(Query.EQ("_id", userId)); if (user == null) { throw new HttpResponseException(request.CreateResponse(HttpStatusCode.NotFound, new APIError("invalidUserId", "Invalid or non-existant user id"))); } var key = from k in user.SessionKeys where k.Key == sessionKey && k.Expires > DateTime.Now select k; if (key.Count() == 0) { throw new HttpResponseException(request.CreateResponse(HttpStatusCode.BadRequest, new APIError("invalidSessionKey", "Invalid, expired or non-existant session key"))); } user.SessionKey = key.First(); var channels = MongoDBHelper.database.GetCollection<Channel>("channels"); user.Channels = ( from c in channels.Find(Query.EQ("Users._id", user.Id)) select new ChannelUserAccess() { Id = c.Name, Access = c.Users.First(x => x.Id == user.Id).Access } ).ToList(); return user; }
public HttpResponseMessage Login(HttpRequestMessage request, LoginViewModel user) { return CreateHttpResponse(request, () => { HttpResponseMessage response = null; if (ModelState.IsValid) { MembershipContext _userContext = _membershipService.ValidateUser(user.Username, user.Password); if (_userContext.user != null) { response = request.CreateResponse(HttpStatusCode.OK, new { success = true }); } else { response = request.CreateResponse(HttpStatusCode.OK, new { success = false }); } } else response = request.CreateResponse(HttpStatusCode.OK, new { success = false }); return response; }); }
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var authenticationHeader = request.Headers.Authorization; HttpResponseMessage response = request.CreateResponse(HttpStatusCode.OK); if (authenticationHeader != null) { var scheme = authenticationHeader.Scheme; var token = authenticationHeader.Parameter; var validToken = _service.GetToken("CloudNotes", token); if (scheme != "Bearer" || validToken == null) { response = request.CreateResponse(HttpStatusCode.Unauthorized); } } else { response = request.CreateResponse(HttpStatusCode.Unauthorized); } var tcs = new TaskCompletionSource<HttpResponseMessage>(); tcs.SetResult(response); return tcs.Task; }
public HttpResponseMessage Get(HttpRequestMessage request, long id) { //this is facebook id if (id > int.MaxValue) { User user = this.dataService.GetUserByFacebookId(id); if (user == null) { return request.CreateResponse(HttpStatusCode.NotFound); } else { return request.CreateResponse<User>(HttpStatusCode.OK, user); } } else { int userId = (int) id; User user = this.dataService.GetUserById(userId); if (user == null) { return request.CreateResponse(HttpStatusCode.NotFound); } else { return request.CreateResponse<User>(HttpStatusCode.OK, user); } } }
public HttpResponseMessage Login(HttpRequestMessage request, LoginViewModel user) { return this.CreateHttpResponse(request, () => { HttpResponseMessage response; // call fluent validator var validateUser = user.Validate(new ValidationContext(user, null, null)); // if no errors returned by fluent validator, continue with the login process if (!validateUser.Any()) { MembershipContext _userContext = _membershipService.ValidateUser(user.Username, user.Password); if (_userContext.User != null) { response = request.CreateResponse(HttpStatusCode.OK, new { success = true }); } else { response = request.CreateResponse(HttpStatusCode.OK, new { success = false }); } } else // LoginViewModel did not pass fluent validation, return unsuccessful response = request.CreateResponse(HttpStatusCode.OK, new { success = false }); return response; }); }
public HttpResponseMessage Put(HttpRequestMessage request, int id, [FromBody]Bet bet) { if (!ModelState.IsValid) { return request.CreateResponse(HttpStatusCode.BadRequest, ModelState); } if (id != bet.Id) { return request.CreateResponse(HttpStatusCode.BadRequest); } try { this.dataService.UpdateBet(bet); } catch (DbUpdateConcurrencyException) { if (dataService.GetBet(id) != null) { return request.CreateResponse(HttpStatusCode.NotFound); } else { throw; } } return request.CreateResponse<Bet>(HttpStatusCode.OK, bet); }
public HttpResponseMessage Login(HttpRequestMessage request, LoginViewModel model) { return CreateHttpResponse(request, () => { HttpResponseMessage response = null; if (ModelState.IsValid) { var context = membershipService.ValidateUser(model.UserName, model.Password); if (context.User != null) { response = request.CreateResponse(HttpStatusCode.OK, new { success = true }); } else { response = request.CreateResponse(HttpStatusCode.OK, new { success = false }); } } else { response = request.CreateResponse(HttpStatusCode.BadRequest, new { success = false }); } return response; }); }
protected HttpResponseMessage CreateHttpRespone(HttpRequestMessage requestMessage, Func<HttpResponseMessage> function) { HttpResponseMessage response = null; try { response = function.Invoke(); } catch (DbEntityValidationException Ex) { foreach (var eve in Ex.EntityValidationErrors) { Trace.WriteLine($"Entity of type \"{eve.Entry.Entity.GetType().Name}\"in state\"{eve.Entry.State}\""); foreach (var ev in eve.ValidationErrors) { Trace.WriteLine($"-Property \"{ev.PropertyName}\", Error:\"{ev.ErrorMessage}\""); } } LogError(Ex); response = requestMessage.CreateResponse(HttpStatusCode.BadRequest, Ex.Message); } catch (DbUpdateException dbEx) { LogError(dbEx); response = requestMessage.CreateResponse(HttpStatusCode.BadRequest, dbEx.InnerException.Message); } catch (Exception ex) { LogError(ex); response = requestMessage.CreateResponse(HttpStatusCode.BadRequest, ex.Message); } return response; }
protected override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { IHttpRouteData routeData = request.GetRouteData(); int key; if(!int.TryParse(routeData.Values["customerkey"].ToString(), out key)) { return Task.FromResult( request.CreateResponse(HttpStatusCode.NotFound) ); } var dependecyScope = request.GetDependencyScope(); var customerRepo = (IEntityRepository<Customer>)dependecyScope.GetService(typeof(IEntityRepository<Customer>)); var customer = customerRepo.GetSingle(key); if (customer == null) { return Task.FromResult( request.CreateResponse(HttpStatusCode.NotFound) ); } return base.SendAsync(request, cancellationToken); }
protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { bool isCsrf = true; CookieHeaderValue cookie = request.Headers .GetCookies(AntiForgeryConfig.CookieName) .FirstOrDefault(); if (cookie != null) { Stream requestBufferedStream = request.Content.ReadAsStreamAsync().Result; requestBufferedStream.Position = 0; NameValueCollection myform = request.Content.ReadAsFormDataAsync().Result; requestBufferedStream.Position = 0; try { AntiForgery.Validate(cookie[AntiForgeryConfig.CookieName].Value, myform[AntiForgeryConfig.CookieName]); isCsrf = false; } catch (Exception ex) { return request.CreateResponse(HttpStatusCode.Forbidden); } } if (isCsrf) { return request.CreateResponse(HttpStatusCode.Forbidden); } return await base.SendAsync(request, cancellationToken); }
protected HttpResponseMessage GetHttpResponse(HttpRequestMessage request, Func<HttpResponseMessage> codeToExecute) { HttpResponseMessage response = null; try { response = codeToExecute.Invoke(); } catch (SecurityException ex) { response = request.CreateResponse(HttpStatusCode.Unauthorized, ex.Message); } catch(FaultException<AuthorizationValidationException> ex) { response = request.CreateResponse(HttpStatusCode.Unauthorized, ex.Message); } catch(FaultException ex) { response = request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message); } catch(Exception ex) { response = request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message); } return response; }
// POST api/values public HttpResponseMessage Post(HttpRequestMessage request, TwilioRequest trequest) { Response tresp = null; var kuser = _session.QueryOver<KUser>().Where(x => x.Mobile == trequest.From).List().FirstOrDefault(); //New acccount flow if (kuser == null) { if (_bodyParser.CommandExists("register", trequest.Body)) tresp = _kService.ProcessCommand("register", trequest); else { tresp = _kService.ProcessCommand("newaccount", trequest); } var responsec = request.CreateResponse(HttpStatusCode.OK, tresp, new XmlMediaTypeFormatter()); //response.Headers.Add("Location", '/api/users'); return responsec; } tresp = _kService.ProcessCommands(trequest); // var response = request.CreateResponse(HttpStatusCode.OK, tresp, new XmlMediaTypeFormatter()); //response.Headers.Add("Location", '/api/users'); return response; }
protected HttpResponseMessage GetHttpResponse(HttpRequestMessage request, Func<HttpResponseMessage> codeToExecute) { HttpResponseMessage response = null; try { response = codeToExecute.Invoke(); } catch (FluentValidation.ValidationException ex) { var result = ex.Errors.Select(item => new System.ComponentModel.DataAnnotations.ValidationResult(item.ErrorMessage, new List<string> { item.PropertyName })); response = request.CreateResponse(HttpStatusCode.BadRequest, result); } //catch (SecurityException ex) //{ // response = request.CreateResponse(HttpStatusCode.Unauthorized, ex.Message); //} //catch (FaultException<AuthorizationValidationException> ex) //{ // response = request.CreateResponse(HttpStatusCode.Unauthorized, ex.Message); //} //catch (FaultException ex) //{ // response = request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message); //} catch (Exception ex) { response = request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message); } return response; }
public HttpResponseMessage ValidateRegistrationStep1(HttpRequestMessage request, [FromBody]AccountRegisterModel accountModel) { return GetHttpResponse(request, () => { HttpResponseMessage response = null; List<string> errors = new List<string>(); // TODO: validate other fields here in case smart-ass user tries to access this API outside of the site #region Commented code //List<State> states = UIHelper.GetStates(); //State state = states.Where(item => item.Abbrev.ToUpper() == accountModel.State.ToUpper()).FirstOrDefault(); //if (state == null) // errors.Add("Invalid state."); //Match matchZipCode = Regex.Match(accountModel.ZipCode, @"^\d{5}(?:[-\s]\d{4})?$"); //if (!matchZipCode.Success) // errors.Add("Zip code is in an invalid format."); #endregion if (errors.Count == 0) response = request.CreateResponse(HttpStatusCode.OK); else response = request.CreateResponse<string[]>(HttpStatusCode.BadRequest, errors.ToArray()); return response; }); }
public HttpResponseMessage GetMyUsers(HttpRequestMessage request) { try { var results = Repository().Query<User>().ToList(); var users = results.Select(u => new UserModel { Id = u.Id, FullName = u.FirstName + ", " + u.LastName, UserName = u.UserName, Email = u.Email, Address1 = u.Address1, PhoneNumber = u.PhoneNumber, Status = u.UserStatus.Name, FirstName = u.FirstName, LastName = u.LastName, Address2 = u.Address2 }).ToList(); return request.CreateResponse(HttpStatusCode.OK, users.ToArray()); } catch (Exception) { return request.CreateResponse(HttpStatusCode.InternalServerError, "error getting users info from db"); } }
public HttpResponseMessage UpdateCustomerAccountInfo(HttpRequestMessage request, Account accountModel) { return GetHttpResponse(request, () => { HttpResponseMessage response = null; ValidateAuthorizedUser(accountModel.LoginEmail); List<string> errors = new List<string>(); List<State> states = UIHelper.GetStates(); State state = states.Where(item => item.Abbrev.ToUpper() == accountModel.State.ToUpper()).FirstOrDefault(); if (state == null) errors.Add("Invalid state."); // trim out the / in the exp date accountModel.ExpDate = accountModel.ExpDate.Substring(0, 2) + accountModel.ExpDate.Substring(3, 2); if (errors.Count == 0) { _AccountService.UpdateCustomerAccountInfo(accountModel); response = request.CreateResponse(HttpStatusCode.OK); } else { response = request.CreateResponse<string[]>(HttpStatusCode.BadRequest, errors.ToArray()); } return response; }); }
public HttpResponseMessage PrepareResponse(HttpRequestMessage request) { try { StringBuilder acknowledgement = new StringBuilder(); acknowledgement.Append("<?xml version = \"1.0\" encoding = \"utf-8\"?>"); acknowledgement.Append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"); acknowledgement.Append("<soapenv:Body>"); acknowledgement.Append("<notifications xmlns=\"http://soap.sforce.com/2005/09/outbound\">"); acknowledgement.Append("<Ack>true</Ack>"); acknowledgement.Append("</notifications>"); acknowledgement.Append("</soapenv:Body>"); acknowledgement.Append("</soapenv:Envelope>"); HttpResponseMessage response = request.CreateResponse(); response.Content = new StreamContent(new MemoryStream(Encoding.UTF8.GetBytes(acknowledgement.ToString()))); response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/xml"); response.StatusCode = HttpStatusCode.OK; return response; } catch (Exception) { //TODO: log exception } return request.CreateResponse(); }
public HttpResponseMessage Add(HttpRequestMessage request, HRMFileDto hrmFileDto) { return CreateHttpResponse(request, () => { HttpResponseMessage response; var athlete = _athleteRepository.GetSingle(hrmFileDto.AthleteId); if (athlete == null) { response = request.CreateErrorResponse(HttpStatusCode.NotFound, "Invalid Athlete"); } else { try { _sessionRepository.Add(hrmFileDto); response = request.CreateResponse(HttpStatusCode.Created); } catch (Exception) { response = request.CreateResponse(HttpStatusCode.BadRequest); } } return response; }); }
public HttpResponseMessage Create(HttpRequestMessage request, FamilyViewModel family) { return CreateHttpResponse(request, () => { HttpResponseMessage response = null; if (!ModelState.IsValid) { response = request.CreateResponse(HttpStatusCode.BadRequest, ModelState.Keys.SelectMany(k => ModelState[k].Errors) .Select(m => m.ErrorMessage).ToArray()); } else { Family newFamily = new Family(); newFamily.UpdateFamily(family); _familyRepository.Add(newFamily); _unitOfWork.Commit(); // Update view model family = Mapper.Map<Family, FamilyViewModel>(newFamily); response = request.CreateResponse<FamilyViewModel>(HttpStatusCode.Created, family); } return response; }); }
public HttpResponseMessage Get(HttpRequestMessage request, ProjectListType type) { UserProfile theUser = _service.GetUserProfile(_security.GetUserId(User.Identity.Name)); IEnumerable<ProjectListViewModel> list; switch (type) { case ProjectListType.IamArchitect: list = _service.GetEnumerable(s => s.ArchitectId == theUser.CompanyId) .Select(s => new ProjectListViewModel { Architect = s.Architect.CompanyName, Id = s.Id, Title = s.Title, Number = s.Number }); return request.CreateResponse(HttpStatusCode.OK, list); case ProjectListType.MyCreated: list = _service.GetEnumerable(s => s.CreatedById == theUser.UserId) .Select(s => new ProjectListViewModel { Architect = s.Architect.CompanyName, Id = s.Id, Title = s.Title, Number = s.Number }); return request.CreateResponse(HttpStatusCode.OK, list); case ProjectListType.InvitedTo: // get invitations to project IEnumerable<Invitation> invites = _service.GetInvitations(theUser.CompanyId); // get the projects var projects = invites.Select(i => i.BidPackage.Project).Distinct(); // convert to view model list = projects.Select(p => new ProjectListViewModel { Id = p.Id, Title = p.Title, Architect = p.Architect.CompanyName, Number = p.Number }); return request.CreateResponse(HttpStatusCode.OK, list); case ProjectListType.Open: list = _service.GetActivePublicSearchable() .Select(s => new ProjectListViewModel { Architect = s.Architect.CompanyName, Id = s.Id, Title = s.Title, Number = s.Number }); return request.CreateResponse(HttpStatusCode.OK, list); default: return request.CreateResponse(HttpStatusCode.BadRequest); } }
//GET: api/Rooms/5 public HttpResponseMessage Get(HttpRequestMessage request, int id) { var room = _RoomRepo.GetAllRooms().Where(r => r.Id == id).FirstOrDefault(); if (room != null) return request.CreateResponse(System.Net.HttpStatusCode.OK, room); else return request.CreateResponse(System.Net.HttpStatusCode.NoContent, room); }
public HttpResponseMessage Post(HttpRequestMessage request, [FromBody]Event value) { if (ModelState.IsValid) { _eventRepository.Add(value); var msg = string.Format("Событие {0} успешно добавленно!", value.Title); return request.CreateResponse(HttpStatusCode.OK, msg); } return request.CreateResponse(HttpStatusCode.BadRequest, GetErrorMessages()); }
public HttpResponseMessage Get(HttpRequestMessage request, int id) { WinningItem winningItem = dataService.GetWinningItem(id); if (winningItem == null) { return request.CreateResponse(HttpStatusCode.NotFound); } return request.CreateResponse<WinningItem>(HttpStatusCode.OK, winningItem); }
public HttpResponseMessage Delete(HttpRequestMessage request, int userId, int betId) { BetUser betUser = this.dataService.RemoveBetUser(betId, userId); if (betUser == null) { return request.CreateResponse(HttpStatusCode.NotFound); } string json = JsonConvert.SerializeObject(betUser); return request.CreateResponse<BetUser>(HttpStatusCode.OK, betUser); }
public HttpResponseMessage Post(HttpRequestMessage request, [FromBody]WinningItem winningItem) { if (!ModelState.IsValid) { return request.CreateResponse(HttpStatusCode.BadRequest, ModelState); } dataService.AddWinningItem(winningItem); string json = JsonConvert.SerializeObject(winningItem); return request.CreateResponse<WinningItem>(HttpStatusCode.OK, winningItem); }
protected HttpResponseMessage CreateHttpResponse(System.Net.Http.HttpRequestMessage request, List <Type> repos, Func <HttpResponseMessage> function) { HttpResponseMessage response = null; try { RequestMessage = request; InitRepositories(repos); response = function.Invoke(); } catch (DbUpdateException ex) { LogError(ex); response = request.CreateResponse(HttpStatusCode.BadRequest, ex.InnerException.Message); } catch (Exception ex) { LogError(ex); response = request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message); } return(response); }
public static void EvalMockingErrorModeActive(JObject json, System.Net.Http.HttpRequestMessage request) { if (ApplicationConfiguration.IsProd()) { return; } var mockerror = json.Property(MockingErrorKey); if (mockerror == null || mockerror.Value.ToString().EqualsIc("false")) { return; } try { object a = new { }; var b = (string)a; } catch (Exception e) { var errorResponse = request.CreateResponse(HttpStatusCode.InternalServerError, new ErrorDto(e.Message, e.StackTrace, e.StackTrace)); throw new HttpResponseException(errorResponse); } }
public HttpResponseMessage Get(string email, string senha) { var configuration = new HttpConfiguration(); var request = new System.Net.Http.HttpRequestMessage(); request.Properties[System.Web.Http.Hosting.HttpPropertyKeys.HttpConfigurationKey] = configuration; try { var usuario = _loginAppService.Login(email, senha); return(request.CreateResponse(HttpStatusCode.OK, usuario)); } catch (Exception e) { return(request.CreateErrorResponse(HttpStatusCode.InternalServerError, e.Message)); } }
public HttpResponseMessage Post(UsuarioViewModel usuarioViewModel) { var configuration = new HttpConfiguration(); var request = new System.Net.Http.HttpRequestMessage(); request.Properties[System.Web.Http.Hosting.HttpPropertyKeys.HttpConfigurationKey] = configuration; try { var usuario = _usuarioAppService.Adicionar(usuarioViewModel); var telefoneViewModel = new TelefoneViewModel(); foreach (var telefone in usuario.Telefones) { // Adicionando os dados do telefone telefoneViewModel.Id = Guid.NewGuid(); telefoneViewModel.Numero = telefone.Numero; telefoneViewModel.Ddd = telefone.Ddd; telefoneViewModel.UsuarioId = usuario.Id; // chamanda o serviço para adicionar o telefone _telefoneAppService.AdicionarTelefone(telefoneViewModel); // Adicionando dados do telefone para retorno telefone.Id = telefoneViewModel.Id; telefone.UsuarioId = telefoneViewModel.UsuarioId; } return(request.CreateResponse(HttpStatusCode.OK, usuario)); } catch (Exception e) { return(request.CreateErrorResponse(HttpStatusCode.InternalServerError, e.Message)); } }
protected override Task <HttpResponseMessage> SendAsync( System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { if (request.Method == System.Net.Http.HttpMethod.Options) { var apiExplorer = GlobalConfiguration.Configuration.Services.GetApiExplorer(); var controllerRequested = request.GetRouteData().Values["controller"] as string; var supportedMethods = apiExplorer.ApiDescriptions .Where(d => { var controller = d.ActionDescriptor.ControllerDescriptor.ControllerName; return(string.Equals( controller, controllerRequested, StringComparison.OrdinalIgnoreCase)); }) .Select(d => d.HttpMethod.Method) .Distinct(); if (supportedMethods != null && supportedMethods.Any() || (controllerRequested ?? "").Equals("ServicesV1", StringComparison.InvariantCultureIgnoreCase)) { return(Task.Factory.StartNew(() => { var resp = new HttpResponseMessage(HttpStatusCode.OK); resp.Headers.Add("Access-Control-Allow-Methods", string.Join(",", supportedMethods.Concat(new[] { "ServicesV1", "ValidateSettings" }))); resp.Headers.Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); return resp; })); } else { return(Task.Factory.StartNew(() => request.CreateResponse(HttpStatusCode.NotFound))); } } return(base.SendAsync(request, cancellationToken)); }
public HttpResponseMessage Get(Guid id) { var configuration = new HttpConfiguration(); var request = new System.Net.Http.HttpRequestMessage(); request.Properties[System.Web.Http.Hosting.HttpPropertyKeys.HttpConfigurationKey] = configuration; // Buscando o Header de Autorização var authorization = Request.Headers.Authorization; var token = authorization.ToString(); try { var usuario = _profilerAppService.ValidarToken(token, id); return(request.CreateResponse(HttpStatusCode.OK, usuario)); } catch (Exception e) { return(request.CreateErrorResponse(HttpStatusCode.InternalServerError, e.Message)); } }
/// <summary> /// Helper method that creates a <see cref="HttpResponseMessage"/> with an <see cref="ObjectContent{T}"/> instance containing the provided /// <paramref name="value"/> and the given <paramref name="formatter"/>. /// </summary> /// <typeparam name="T">The type of the value.</typeparam> /// <param name="request">The request.</param> /// <param name="statusCode">The status code of the created response.</param> /// <param name="value">The value to wrap. Can be <c>null</c>.</param> /// <param name="formatter">The formatter to use.</param> /// <param name="mediaType">The media type override to set on the response's content. Can be <c>null</c>.</param> /// <returns>A response wrapping <paramref name="value"/> with <paramref name="statusCode"/>.</returns> public static HttpResponseMessage CreateResponse <T>(this HttpRequestMessage request, HttpStatusCode statusCode, T value, MediaTypeFormatter formatter, string mediaType) { MediaTypeHeaderValue mediaTypeHeader = mediaType != null ? new MediaTypeHeaderValue(mediaType) : null; return(request.CreateResponse(statusCode, value, formatter, mediaTypeHeader)); }
/// <summary> /// Helper method that creates a <see cref="HttpResponseMessage"/> with an <see cref="ObjectContent{T}"/> instance containing the provided /// <paramref name="value"/> and the given <paramref name="formatter"/>. /// </summary> /// <typeparam name="T">The type of the value.</typeparam> /// <param name="request">The request.</param> /// <param name="statusCode">The status code of the created response.</param> /// <param name="value">The value to wrap. Can be <c>null</c>.</param> /// <param name="formatter">The formatter to use.</param> /// <returns>A response wrapping <paramref name="value"/> with <paramref name="statusCode"/>.</returns> public static HttpResponseMessage CreateResponse <T>(this HttpRequestMessage request, HttpStatusCode statusCode, T value, MediaTypeFormatter formatter) { return(request.CreateResponse(statusCode, value, formatter, (MediaTypeHeaderValue)null)); }
/// <summary> /// Helper method that creates a <see cref="HttpResponseMessage"/> with an <see cref="ObjectContent{T}"/> instance containing the provided /// <paramref name="value"/>. The given <paramref name="mediaType"/> is used to find an instance of <see cref="MediaTypeFormatter"/>. /// </summary> /// <typeparam name="T">The type of the value.</typeparam> /// <param name="request">The request.</param> /// <param name="statusCode">The status code of the created response.</param> /// <param name="value">The value to wrap. Can be <c>null</c>.</param> /// <param name="mediaType">The media type used to look up an instance of <see cref="MediaTypeFormatter"/>.</param> /// <exception cref="InvalidOperationException">Thrown if the <paramref name="request"/> does not have an associated /// <see cref="HttpConfiguration"/> instance or if the configuration does not have a formatter matching <paramref name="mediaType"/>.</exception> /// <returns>A response wrapping <paramref name="value"/> with <paramref name="statusCode"/>.</returns> public static HttpResponseMessage CreateResponse <T>(this HttpRequestMessage request, HttpStatusCode statusCode, T value, string mediaType) { return(request.CreateResponse(statusCode, value, new MediaTypeHeaderValue(mediaType))); }
/// <summary> /// Helper method that performs content negotiation and creates a <see cref="HttpResponseMessage"/> with an instance /// of <see cref="ObjectContent{T}"/> as the content if a formatter can be found. If no formatter is found, this /// method returns a response with status 406 NotAcceptable. This forwards the call to /// <see cref="CreateResponse{T}(HttpRequestMessage, HttpStatusCode, T, HttpConfiguration)"/> with a <c>null</c> /// configuration. /// </summary> /// <remarks> /// This method requires that <paramref name="request"/> has been associated with an instance of /// <see cref="HttpConfiguration"/>. /// </remarks> /// <typeparam name="T">The type of the value.</typeparam> /// <param name="request">The request.</param> /// <param name="statusCode">The status code of the created response.</param> /// <param name="value">The value to wrap. Can be <c>null</c>.</param> /// <returns>A response wrapping <paramref name="value"/> with <paramref name="statusCode"/>.</returns> public static HttpResponseMessage CreateResponse <T>(this HttpRequestMessage request, HttpStatusCode statusCode, T value) { return(request.CreateResponse <T>(statusCode, value, configuration: null)); }
/// <summary> /// Helper method that performs content negotiation and creates a <see cref="HttpResponseMessage"/> with an instance /// of <see cref="ObjectContent{T}"/> as the content and <see cref="System.Net.HttpStatusCode.OK"/> as the status code /// if a formatter can be found. If no formatter is found, this method returns a response with status 406 NotAcceptable. /// </summary> /// <remarks> /// This method requires that <paramref name="request"/> has been associated with an instance of /// <see cref="HttpContext"/>. /// </remarks> /// <typeparam name="T">The type of the value.</typeparam> /// <param name="request">The request.</param> /// <param name="value">The value to wrap. Can be <c>null</c>.</param> /// <returns>A response wrapping <paramref name="value"/> with <see cref="System.Net.HttpStatusCode.OK"/> status code.</returns> public static HttpResponseMessage CreateResponse <T>([NotNull] this HttpRequestMessage request, T value) { return(request.CreateResponse <T>(HttpStatusCode.OK, value, formatters: null)); }
/// <summary> /// Helper method that performs content negotiation and creates a <see cref="HttpResponseMessage"/> with an instance /// of <see cref="ObjectContent{T}"/> as the content if a formatter can be found. If no formatter is found, this /// method returns a response with status 406 NotAcceptable. /// configuration. /// </summary> /// <remarks> /// This method requires that <paramref name="request"/> has been associated with an instance of /// <see cref="HttpContext"/>. /// </remarks> /// <typeparam name="T">The type of the value.</typeparam> /// <param name="request">The request.</param> /// <param name="statusCode">The status code of the created response.</param> /// <param name="value">The value to wrap. Can be <c>null</c>.</param> /// <returns>A response wrapping <paramref name="value"/> with <paramref name="statusCode"/>.</returns> public static HttpResponseMessage CreateResponse <T>(this HttpRequestMessage request, HttpStatusCode statusCode, T value) { return(request.CreateResponse <T>(statusCode, value, formatters: null)); }
public HttpResponseMessage Delete(HttpRequestMessage request, int projectId) { Project theProject = _service.GetProject(projectId); if (theProject == null) { return request.CreateResponse(HttpStatusCode.NotFound, "project not found"); } int companyId = _service.GetUserProfile(_security.GetUserId(User.Identity.Name)).CompanyId; // get master bp because that is what gc's bid to. BidPackage bidPackage = theProject.BidPackages.Where(x => x.IsMaster).SingleOrDefault(); Invitation selfInvite = _service.Get(bidPackage.Id, companyId); if (selfInvite == null) { return request.CreateResponse(HttpStatusCode.NotFound, "you have not proffered to join this project"); } selfInvite.RejectedDate = DateTime.Now; selfInvite.AcceptedDate = default(DateTime?); if (_service.Update(selfInvite)) { _notice.SendInviteResponse(bidPackage.Id); return request.CreateResponse(HttpStatusCode.OK, new { date = selfInvite.RejectedDate.Value.ToShortDateString() }); } else { return request.CreateResponse(HttpStatusCode.InternalServerError); } }
public HttpResponseMessage ChangePassword(HttpRequestMessage request, int operationResult) { Result res = new Result(); res.result = "修改密码失败"; var resp = request.CreateResponse(HttpStatusCode.InternalServerError, res); switch (operationResult) { case 1: res.result = "修改密码成功"; resp = request.CreateResponse(HttpStatusCode.OK, res); break; case 2: res.result = "修改密码失败"; resp = request.CreateResponse(HttpStatusCode.InternalServerError, res); break; case 3: res.result = "旧密码错误,请输入正确的旧密码"; resp = request.CreateResponse(HttpStatusCode.BadRequest, res); break; case 4: res.result = "密码已过期,请联系管理员重置密码"; resp = request.CreateResponse(HttpStatusCode.BadRequest, res); break; default: break; } return resp; }