當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。