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


C# HttpRequestMessage.CreateErrorResponse方法代码示例

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


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

示例1: ProcessVersionHeader

        protected virtual string ProcessVersionHeader(HttpRequestMessage request, string odataPath)
        {
            var apiVersion = request.Headers.Where(kv => kv.Key.Equals(VersionMap.VersionHeaderName, StringComparison.InvariantCultureIgnoreCase)).SelectMany(kv => kv.Value).FirstOrDefault();

            int version = -1;
            if (string.IsNullOrWhiteSpace(apiVersion))
            {
                version = VersionMap.CurrentVersion;
            }
            else if (!int.TryParse(apiVersion, out version))
            {
                throw new HttpResponseException(request.CreateErrorResponse(HttpStatusCode.BadRequest, "Invalid Api Version specified: " + apiVersion));
            }

            if (version < VersionMap.MinVersion || version > VersionMap.CurrentVersion) goto UnsupportedVersion;

            var endpoint = odataPath;

            var targetEndpoint = VersionMap.GetEndpointName(version, endpoint);
            if (targetEndpoint == null) goto UnsupportedVersion;

            return targetEndpoint;
            UnsupportedVersion:
            throw new HttpResponseException(request.CreateErrorResponse(HttpStatusCode.NotAcceptable, string.Format("Unsupported Api Version specified: {0}. Current version: {1}",  version, VersionMap.CurrentVersion)));
        }
开发者ID:jordansjones,项目名称:ODataVersioning,代码行数:25,代码来源:VersionAwareODataPathHandler.cs

示例2: SendAsync

        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            HttpRequestMessage proxiedRequest = null;

            try
            {
                var hostDetails = await apiSettingsData.GetAsync(request.RequestUri);
                if (hostDetails == null)
                {
                    return request.CreateErrorResponse(HttpStatusCode.NotFound, string.Format("Host '{0}' not recognised as a valid chaos api", request.RequestUri.Host));
                }

                var apiToForwardToHostName = hostDetails.ForwardApiHostName;

                proxiedRequest = CreateNewRequestToProxiedApi(request, hostDetails, apiToForwardToHostName);

                var client = await CreateHttpClientForProxiedRequest(apiToForwardToHostName);

                return await client.SendAsync(proxiedRequest, cancellationToken);
            }
            catch (TaskCanceledException)
            {
                return cancellationToken.IsCancellationRequested
                           ? request.CreateErrorResponse(HttpStatusCode.RequestTimeout, string.Format("Request forward to '{0}' failed, request timed out", proxiedRequest.RequestUri))
                           : request.CreateErrorResponse(HttpStatusCode.InternalServerError, string.Format("Request forward to '{0}' failed, ", proxiedRequest.RequestUri));
            }
            catch (Exception ex)
            {
                return request.CreateErrorResponse(HttpStatusCode.InternalServerError, string.Format("Request forward to '{0}' failed, {1}", proxiedRequest.RequestUri, ex));
            }
        }
开发者ID:dylan-asos,项目名称:Chaos.WebApi,代码行数:31,代码来源:ChaosProxyDelegatingHandler.cs

示例3: SendAsync

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            const string TOKEN_NAME = "X-Token";

            if (request.Headers.Contains(TOKEN_NAME))
            {
                string encryptedToken = request.Headers.GetValues(TOKEN_NAME).First();
                try
                {
                    Token token = Token.Decrypt(encryptedToken);
                    bool isValidUserId = identityStore.IsValidUserId(token.UserId);
                    bool requestIPMatchesTokenIP = token.IP.Equals(request.GetClientIP());

                    if (!isValidUserId || !requestIPMatchesTokenIP)
                    {
                        HttpResponseMessage reply = request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Invalid indentity or client machine.");
                        return Task.FromResult(reply);
                    }
                }
                catch (Exception ex)
                {
                    HttpResponseMessage reply = request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Invalid token.");
                    return Task.FromResult(reply);
                }
            }
            else
            {
                HttpResponseMessage reply = request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Request is missing authorization token.");
                return Task.FromResult(reply);
            }

            return base.SendAsync(request, cancellationToken);
        }
开发者ID:uuksu,项目名称:OwinSelfhostSample,代码行数:33,代码来源:TokenInspector.cs

示例4: Response

        private HttpResponseMessage Response(HttpRequestMessage request)
        {
            const string defaultPageName = "index.html";
            var path = request.RequestUri.AbsolutePath;
            var suffix = path == string.Empty ? defaultPageName : path.Substring(1);
            var fullPath = Path.Combine(m_BaseFolder, suffix);

            if (!File.Exists(fullPath))
            {
                return request.CreateErrorResponse(
                    HttpStatusCode.NotFound,
                    string.Format("Sorry about that, but there is no file named '{0}' here.", suffix));
            }

            string extension = Path.GetExtension(path);
            FileType fileType;
            if (!m_FileTypes.TryGetValue(extension, out fileType))
            {
                return request.CreateErrorResponse(
                    HttpStatusCode.UnsupportedMediaType,
                    string.Format("Sorry I can not process files like '{0}'.", extension));
            }

            var response = request.CreateResponse();
            var fileStream = new FileStream(fullPath, FileMode.Open);
            response.Content = new StreamContent(fileStream);
            response.Content.Headers.ContentType = fileType.ContentType;
            return response;
        }
开发者ID:jklipp,项目名称:codegravity,代码行数:29,代码来源:WebServerOnFolder.cs

示例5: CreateErrorResponse

        public static HttpResponseMessage CreateErrorResponse(Exception throwException, HttpRequestMessage request)
        {
            // Here are some examples of how certain exceptions can be mapped to error responses.
            if (throwException is System.ComponentModel.DataAnnotations.ValidationException)
            {
                // Return when the supplied model (command or query) isn't valid.
                return request.CreateResponse<ValidationResult>(HttpStatusCode.BadRequest,
                    ((ValidationException)throwException).ValidationResult);
            }

            if (throwException is OptimisticConcurrencyException)
            {
                // Return when there was a concurrency conflict in updating the model.
                return request.CreateErrorResponse(HttpStatusCode.Conflict, throwException);
            }

            if (throwException is BusinessLayer.CrossCuttingConcerns.AuthorizationException)
            {
                // Return when the current user doesn't have the proper rights to execute the requested operation
                // or to access the requested resource.
                return request.CreateErrorResponse(HttpStatusCode.Unauthorized, throwException);
            }

            if (throwException is System.Collections.Generic.KeyNotFoundException)
            {
                // Return when the requested resource does not exist anymore. Catching a KeyNotFoundException
                // is an example, but you probably shouldn't throw KeyNotFoundException in this case, since it
                // could be thrown for other reasons (such as program errors) in which case this branch should
                // of course not execute.
                return request.CreateErrorResponse(HttpStatusCode.NotFound, throwException);
            }

            // If the throwException can't be handled: return null.
            return null;
        }
开发者ID:brentarias,项目名称:solidservices,代码行数:35,代码来源:WebApiExceptionTranslator.cs

示例6: SelectController

        public override HttpControllerDescriptor SelectController(HttpRequestMessage request)
        {
            Type type;
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }
            string controllerName = this.GetControllerName(request);
            if (string.IsNullOrEmpty(controllerName))
            {
                throw new HttpResponseException(request.CreateErrorResponse(HttpStatusCode.NotFound,
                    string.Format("No route providing a controller name was found to match request URI '{0}'",
                    new object[] { request.RequestUri })));
            }
            IEnumerable<string> fullNames = GetControllerFullName(request, controllerName);
            if (fullNames.Count() == 0)
            {
                throw new HttpResponseException(request.CreateErrorResponse(HttpStatusCode.NotFound,
                        string.Format("No route providing a controller name was found to match request URI '{0}'",
                        new object[] { request.RequestUri })));
            }

            if (this._apiControllerCache.Value.TryGetValue(fullNames.First(), out type))
            {
                return new HttpControllerDescriptor(_configuration, controllerName, type);
            }
            throw new HttpResponseException(request.CreateErrorResponse(HttpStatusCode.NotFound,
                string.Format("No route providing a controller name was found to match request URI '{0}'",
                new object[] { request.RequestUri })));
        }
开发者ID:daixinkai,项目名称:Dai.CommonLib,代码行数:30,代码来源:NamespaceHttpControllerSelector.cs

示例7: Login

        public HttpResponseMessage Login(HttpRequestMessage requestMsg)
        {
            var request = new HttpContextWrapper(HttpContext.Current).Request;

            if (request.Form["username"] == null || request.Form["password"] == null)
            {
                return requestMsg.CreateErrorResponse(
                    HttpStatusCode.BadRequest,
                    new ArgumentException("Unable to find username or password.")
                );
            }

            var loginDictionnary = this.AuthService.Login(
                request.Form["username"],
                request.Form["password"]
            );

            if (loginDictionnary != null)
            {
                return requestMsg.CreateResponse(
                    HttpStatusCode.OK,
                    loginDictionnary
                );
            }

            return requestMsg.CreateErrorResponse(
                HttpStatusCode.Forbidden,
                "Wrong credentials"
            );
        }
开发者ID:christophedebatz,项目名称:JoulsePower,代码行数:30,代码来源:AuthController.cs

示例8: SendAsync

        /// <summary>
        /// 以异步操作发送 HTTP 请求到内部管理器以发送到服务器。
        /// </summary>
        /// <returns>
        /// 返回 <see cref="T:System.Threading.Tasks.Task`1"/>。 表示异步操作的任务对象。
        /// </returns>
        /// <param name="request">要发送到服务器的 HTTP 请求消息。</param>
        /// <param name="cancellationToken">取消操作的取消标记。</param>
        /// <exception cref="T:System.ArgumentNullException"> <paramref name="request"/> 为 null。</exception>
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var result = EncryptRequest(request);
            if (result != null)
            {
                return result;
            }
            return base.SendAsync(request, cancellationToken)
                .ContinueWith(task =>
                {
                    if (task.IsFaulted)
                    {
                        var aggregateException = task.Exception;
                        if (aggregateException != null)
                        {
                            var requestException = aggregateException.InnerExceptions.FirstOrDefault(m => m is HttpRequestException);
                            if (requestException != null && requestException.InnerException is WebException)
                            {
                                return request.CreateErrorResponse(HttpStatusCode.ServiceUnavailable, requestException.InnerException);
                            }
                        }

                        return request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, task.Exception);
                    }
                    return DecryptResponse(task.Result);
                }, cancellationToken);
        }
开发者ID:yonghu86,项目名称:osharp,代码行数:36,代码来源:ClientCryptoDelegatingHandler.cs

示例9: SendAsync

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            IEnumerable<string> userNameHeaderValues = null;
            if (request.Headers.TryGetValues(KawalDesaHeaders.X_KD_USERID, out userNameHeaderValues))
            {
                if (!IsValidEmissRequest(request))
                {
                    var response = request.CreateErrorResponse(HttpStatusCode.BadRequest, "Not a Valid Request");
                    return Task.FromResult<HttpResponseMessage>(response);
                }

                IEnumerable<String> expireHeaderValues = null;
                if (request.Headers.TryGetValues(KawalDesaHeaders.X_KD_EXPIRES, out expireHeaderValues))
                {
                    if (IsExpiredRequest(expireHeaderValues.FirstOrDefault()))
                    {
                        var response = request.CreateErrorResponse(HttpStatusCode.BadRequest, "Your Request Has Expired");
                        return Task.FromResult<HttpResponseMessage>(response);
                    }
                }

                var userName = userNameHeaderValues.First();
                var userManager = new UserManager<User>(new CUserStore<User>(new DB()));
                var user = userManager.FindByName(userName);
                if (user != null)
                {
                    string signature = CryptographyHelper.Sign(request, user.SecretKey);
                    if (signature.Equals(request.Headers.GetValues(KawalDesaHeaders.X_KD_SIGNATURE).FirstOrDefault()))
                    {
                        var identity = new KawalDesaIdentity(user, "Emiss");
                        var principal = new GenericPrincipal(identity, userManager.GetRoles(user.Id).ToArray());
                        Thread.CurrentPrincipal = principal;
                        if (HttpContext.Current != null)
                        {
                            HttpContext.Current.User = principal;
                        }
                    }
                }
            }
            else if (HttpContext.Current.Session != null && !String.IsNullOrEmpty((string)HttpContext.Current.Session[KawalDesaController.USERID_KEY]))
            {
                var session = HttpContext.Current.Session;
                var userManager = new UserManager<User>(new CUserStore<User>(new DB()));
                var user = userManager.FindById((string)session[KawalDesaController.USERID_KEY]);
                if (user != null)
                {
                    var identity = new KawalDesaIdentity(user, "Session");
                    var principal = new GenericPrincipal(identity, userManager.GetRoles(user.Id).ToArray());
                    Thread.CurrentPrincipal = principal;
                    if (HttpContext.Current != null)
                    {
                        HttpContext.Current.User = principal;
                    }
                }
            }

            return base.SendAsync(request, cancellationToken);
        }
开发者ID:nazhir,项目名称:kawaldesa,代码行数:58,代码来源:AuthorizationHandler.cs

示例10: ReceiveAsync

        /// <inheritdoc />
        public override async Task<HttpResponseMessage> ReceiveAsync(string receiver, HttpRequestContext context, HttpRequestMessage request)
        {
            if (receiver == null)
            {
                throw new ArgumentNullException("receiver");
            }
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            if (request.Method == HttpMethod.Post)
            {
                EnsureSecureConnection(request);

                // Read the request entity body
                NameValueCollection data = await ReadAsFormDataAsync(request);

                // Verify that the token is correct
                string token = data[TokenParameter];
                string secretKey = GetWebHookSecret(request, SecretKey, 8, 64);
                if (!WebHookReceiver.SecretEqual(token, secretKey))
                {
                    string msg = string.Format(CultureInfo.CurrentCulture, SlackReceiverResources.Receiver_BadToken, TokenParameter);
                    context.Configuration.DependencyResolver.GetLogger().Error(msg);
                    HttpResponseMessage invalidCode = request.CreateErrorResponse(HttpStatusCode.BadRequest, msg);
                    return invalidCode;
                }

                // Get the action
                string action = data[ActionParameter];
                if (string.IsNullOrEmpty(action))
                {
                    string msg = string.Format(CultureInfo.CurrentCulture, SlackReceiverResources.Receiver_BadBody, ActionParameter);
                    context.Configuration.DependencyResolver.GetLogger().Error(msg);
                    HttpResponseMessage badType = request.CreateErrorResponse(HttpStatusCode.BadRequest, msg);
                    return badType;
                }

                // Get the subtext by removing the trigger word
                string text = data[TextParameter];
                data[SubtextParameter] = GetSubtext(action, text);

                // Call registered handlers
                return await ExecuteWebHookAsync(receiver, context, request, new string[] { action }, data);
            }
            else
            {
                return CreateBadMethodResponse(request);
            }
        }
开发者ID:Joshzx,项目名称:WebHooks,代码行数:56,代码来源:SlackWebHookReceiver.cs

示例11: Process

        public static HttpResponseMessage Process(HttpRequestMessage request)
        {
            // Check if the request contains multipart/form-data.
            if (!request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            try
            {
                Stream reqStream = request.Content.ReadAsStreamAsync().Result;
                MemoryStream tempStream = new MemoryStream();
                reqStream.CopyTo(tempStream);
                
                tempStream.Seek(0, SeekOrigin.End);
                Log.Submit(LogLevel.Debug, "Upload request has " + tempStream.Length + " bytes");
                tempStream.Position = 0;
                
                StreamContent streamContent = new StreamContent(tempStream);
                foreach (KeyValuePair<string, IEnumerable<string>> header in request.Content.Headers)
                {
                    streamContent.Headers.Add(header.Key, header.Value);
                    Log.Submit(LogLevel.Debug, "Header " + header.Key + ": " + string.Join(",", header.Value));
                }

                MultipartFormDataParser parser = new MultipartFormDataParser(tempStream);

                // This illustrates how to get the file names.
                FilePart file = parser.Files.FirstOrDefault();
                if (parser.Files == null || parser.Files.Count != 1)
                    throw new InvalidOperationException();
                if (file == null || file.FileName != "package")
                    throw new InvalidOperationException();

                PackageDAO.ProcessPackage(file.Data);

                return request.CreateResponse(HttpStatusCode.Created);
            }
            catch (AlreadyExistsException e)
            {
                Log.SubmitException(e);
                return request.CreateErrorResponse(HttpStatusCode.Conflict, e);
            }
            catch (InvalidOperationException e)
            {
                Log.SubmitException(e);
                return request.CreateErrorResponse(HttpStatusCode.BadRequest, e);
            }
            catch (Exception e)
            {
                Log.SubmitException(e);
                return request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
            }
        }
开发者ID:abelsilva,项目名称:nugetory,代码行数:54,代码来源:UploadPackage.cs

示例12: ReceiveAsync

        /// <inheritdoc />
        public override async Task<HttpResponseMessage> ReceiveAsync(string id, HttpRequestContext context, HttpRequestMessage request)
        {
            if (id == null)
            {
                throw new ArgumentNullException("id");
            }
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            if (request.Method == HttpMethod.Post)
            {
                // Ensure that we use https and have a valid code parameter
                await EnsureValidCode(request, id);

                // Read the request entity body.
                JObject data = await ReadAsJsonAsync(request);

                // Pick out action from headers
                IEnumerable<string> actions;
                if (!request.Headers.TryGetValues(EventHeaderKey, out actions))
                {
                    string msg = string.Format(CultureInfo.CurrentCulture, BitbucketReceiverResources.Receiver_NoEvent, EventHeaderKey);
                    context.Configuration.DependencyResolver.GetLogger().Error(msg);
                    HttpResponseMessage noEventHeader = request.CreateErrorResponse(HttpStatusCode.BadRequest, msg);
                    return noEventHeader;
                }

                // Get the WebHook ID
                IEnumerable<string> webHookId;
                if (!request.Headers.TryGetValues(UUIDHeaderName, out webHookId))
                {
                    string msg = string.Format(CultureInfo.CurrentCulture, BitbucketReceiverResources.Receiver_NoId, UUIDHeaderName);
                    context.Configuration.DependencyResolver.GetLogger().Error(msg);
                    HttpResponseMessage noWebHookIdHeader = request.CreateErrorResponse(HttpStatusCode.BadRequest, msg);
                    return noWebHookIdHeader;
                }

                // Set the WebHook ID in the payload
                data[WebHookIdKey] = webHookId.FirstOrDefault();

                // Call registered handlers
                return await ExecuteWebHookAsync(id, context, request, actions, data);
            }
            else
            {
                return CreateBadMethodResponse(request);
            }
        }
开发者ID:itomek,项目名称:WebHooks,代码行数:55,代码来源:BitbucketWebHookReceiver.cs

示例13: GetContactCompany

        public HttpResponseMessage GetContactCompany(HttpRequestMessage request, int id)
        {
            var result = this.ContactDao.GetById(id);

            if (result == null) {
                return request.CreateErrorResponse(HttpStatusCode.NotFound, "Contact not found.");
            }

            return result.Company != null
                ? request.CreateResponse(HttpStatusCode.OK, result.Company)
                : request.CreateErrorResponse(HttpStatusCode.NotFound, "This contact has no company");
        }
开发者ID:christophedebatz,项目名称:JoulsePower,代码行数:12,代码来源:ContactController.cs

示例14: Post

        public HttpResponseMessage Post(HttpRequestMessage request, Order order)
        {
            if (!order.Items.Any())
                return request.CreateErrorResponse(HttpStatusCode.BadRequest, "Order has no items");

            if(_orderService.Exists(order.Id))
                return request.CreateErrorResponse(HttpStatusCode.BadRequest, "Order already exists");

            _orderService.Save(order);
            var response = request.CreateResponse(HttpStatusCode.Created);
            response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = order.Id }));
            return response;
        }
开发者ID:tugberkugurlu,项目名称:ProWebAPI.Samples,代码行数:13,代码来源:OrderController.cs

示例15: ConsumeExceptionFromStore

        protected IHttpActionResult ConsumeExceptionFromStore(HttpRequestMessage req, AggregateException ex)
        {
            if (req!=null && ex !=null) {
                HttpStatusCode code = HttpStatusCode.InternalServerError;

                if (ex.InnerException is IOException) {
                    code = HttpStatusCode.InternalServerError;
                }
                else if (ex.InnerException is ArgumentException) {
                    code = HttpStatusCode.BadRequest;
                }
                return ResponseMessage(req.CreateErrorResponse(code, ex.InnerException.Message));
            }
            return ResponseMessage(req.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unexpected error while consuming the exception from the store"));
        }
开发者ID:CrackDataPots,项目名称:legallyright,代码行数:15,代码来源:BaseController.cs


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