当前位置: 首页>>代码示例>>C#>>正文


C# HttpRequestMessage.CreateResponse方法代码示例

本文整理汇总了C#中System.Net.Http.HttpRequestMessage.CreateResponse方法的典型用法代码示例。如果您正苦于以下问题:C# HttpRequestMessage.CreateResponse方法的具体用法?C# HttpRequestMessage.CreateResponse怎么用?C# HttpRequestMessage.CreateResponse使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Net.Http.HttpRequestMessage的用法示例。


在下文中一共展示了HttpRequestMessage.CreateResponse方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: ChangePassword

        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;
        }
开发者ID:wfguanhan,项目名称:CDMISrestful,代码行数:30,代码来源:ExceptionHandler.cs

示例2: ValidateRegistrationStep1

        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;
            });
        }
开发者ID:oscarlagatta,项目名称:HN.Pim,代码行数:29,代码来源:AccountApiController.cs

示例3: Register

        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;
            });
        }
开发者ID:MarcoWagener,项目名称:SolistenManager,代码行数:27,代码来源:ClientsController.cs

示例4: GetMyUsers

 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");
     }
 }
开发者ID:kingtrocko,项目名称:CellphoneAirTimeApp,代码行数:25,代码来源:SecurityApiController.cs

示例5: Delete

        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);
            }
        }
开发者ID:JoshIBrown,项目名称:BidChuck,代码行数:34,代码来源:ProjectProfferController.cs

示例6: UpdateCustomerAccountInfo

        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;
            });
        }
开发者ID:jalvarezz,项目名称:CarRental,代码行数:31,代码来源:CustomerApiController.cs

示例7: Post

        // 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;
        }
开发者ID:jaxxbo,项目名称:kwickapi,代码行数:27,代码来源:TextServicesController.cs

示例8: Add

        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;
            });
        }
开发者ID:joehoughton,项目名称:cycle-analysis-software,代码行数:28,代码来源:SessionsController.cs

示例9: Put

        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);
        }
开发者ID:SeanNguyen,项目名称:SimpleBetAspNet4,代码行数:28,代码来源:BetController.cs

示例10: Post

        // 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
                    }));
        }
开发者ID:modembug,项目名称:UrlShrinker,代码行数:34,代码来源:EntryController.cs

示例11: Login

        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;
            });
        }
开发者ID:joehoughton,项目名称:cycle-analysis-software,代码行数:29,代码来源:AccountController.cs

示例12: CreateHttpRespone

 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;
 }
开发者ID:thanhqb13293,项目名称:ShopThanh,代码行数:32,代码来源:ApiControllerBase.cs

示例13: SendAsync

        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);
        }
开发者ID:tugberkugurlu,项目名称:AdvancedWebAPI,代码行数:25,代码来源:CustomerOrdersDispatcher.cs

示例14: Login

        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;
            });
        }
开发者ID:steveharan,项目名称:Phoenix,代码行数:25,代码来源:AccountController.cs

示例15: GetHttpResponse

 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;
 }
开发者ID:nayan112,项目名称:HelloWorld,代码行数:25,代码来源:ApiControllerBase.cs


注:本文中的System.Net.Http.HttpRequestMessage.CreateResponse方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。