• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# IResponse类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中IResponse的典型用法代码示例。如果您正苦于以下问题:C# IResponse类的具体用法?C# IResponse怎么用?C# IResponse使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



IResponse类属于命名空间,在下文中一共展示了IResponse类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: SetUp

 public void SetUp()
 {
     request = MockRepository.GenerateStub<IRequest>();
     response = MockRepository.GenerateStub<IResponse>();
     engine = MockRepository.GenerateStub<ILessEngine>();
     lessSource = MockRepository.GenerateStub<ILessSource>();
 }
开发者ID:jongalloway,项目名称:nLess,代码行数:7,代码来源:HandlerFixture.cs


示例2: Evaluate

 /// <summary>
 /// Evaluates the response.
 /// </summary>
 /// <param name="response">The response to parse.</param>
 /// <param name="options">The options to consider.</param>
 public void Evaluate(IResponse response, ScriptOptions options)
 {
     var reader = new StreamReader(response.Content, options.Encoding ?? Encoding.UTF8, true);
     var content = reader.ReadToEnd();
     reader.Close();
     Evaluate(content, options);
 }
开发者ID:AlgorithmsAreCool,项目名称:AngleSharp.Scripting,代码行数:12,代码来源:JavaScriptEngine.cs


示例3: ProcessRequest

        public override void ProcessRequest(IRequest httpReq, IResponse httpRes, string operationName)
        {
            HostContext.ApplyCustomHandlerRequestFilters(httpReq, httpRes);
            if (httpRes.IsClosed) return;

            httpRes.ContentType = MimeTypes.Html;
            if (RazorFormat == null)
                RazorFormat = RazorFormat.Instance;

            var contentPage = RazorPage ?? RazorFormat.FindByPathInfo(PathInfo);
            if (contentPage == null)
            {
                httpRes.StatusCode = (int)HttpStatusCode.NotFound;
                httpRes.EndHttpHandlerRequest();
                return;
            }

            var model = Model;
            if (model == null)
                httpReq.Items.TryGetValue("Model", out model);
            if (model == null)
            {
                var modelType = RazorPage != null ? RazorPage.ModelType : null;
                model = modelType == null || modelType == typeof(DynamicRequestObject)
                    ? null
                    : DeserializeHttpRequest(modelType, httpReq, httpReq.ContentType);
            }

            RazorFormat.ProcessRazorPage(httpReq, contentPage, model, httpRes);
        }
开发者ID:tystol,项目名称:ServiceStack,代码行数:30,代码来源:RazorHandler.cs


示例4: Execute

        public override void Execute(IRequest req, IResponse res, object requestDto)
        {
            var authErrorMessage = "";
            try
            {
                // Perform security check
                if (CanExecute(req))
                    return;
            }
            catch (System.Exception ex)
            {
                authErrorMessage = ex.Message;
                var message = string.Format("Blocked unauthorized request: {0} {1} by ip = {2} due to {3}",
                    req.Verb,
                    req.AbsoluteUri,
                    req.UserHostAddress ?? "unknown",
                    authErrorMessage);
                Log.Error(message);
            }

            // Security failed!
            var responseMessage = "You are not authorized. " + authErrorMessage;

            res.StatusCode = (int)HttpStatusCode.Unauthorized;
            res.StatusDescription = responseMessage;
            res.AddHeader(HttpHeaders.WwwAuthenticate, string.Format("{0} realm=\"{1}\"", "", "custom api"));
            res.ContentType = "text/plain";
            res.Write(responseMessage);
            res.Close();
        }
开发者ID:CodeRevver,项目名称:notekeeper-api,代码行数:30,代码来源:AuthSignatureRequired.cs


示例5: ProcessRequest

		public override void ProcessRequest(IRequest httpReq, IResponse httpRes, string operationName)
    	{
            if (!AssertAccess(httpReq, httpRes, httpReq.QueryString["op"])) return;

			var operationTypes = HostContext.Metadata.GetAllTypes();

    		if (httpReq.QueryString["xsd"] != null)
    		{
				var xsdNo = Convert.ToInt32(httpReq.QueryString["xsd"]);
                var schemaSet = XsdUtils.GetXmlSchemaSet(operationTypes);
    			var schemas = schemaSet.Schemas();
    			var i = 0; 
    			if (xsdNo >= schemas.Count)
    			{
    				throw new ArgumentOutOfRangeException("xsd");
    			}
    			httpRes.ContentType = "text/xml";
    			foreach (XmlSchema schema in schemaSet.Schemas())
    			{
    				if (xsdNo != i++) continue;
    				schema.Write(httpRes.OutputStream);
    				break;
    			}
    			return;
    		}

			using (var sw = new StreamWriter(httpRes.OutputStream))
			{
				var writer = new HtmlTextWriter(sw);
				httpRes.ContentType = "text/html";
				ProcessOperations(writer, httpReq, httpRes);
			}
    	}
开发者ID:vebin,项目名称:soa,代码行数:33,代码来源:BaseSoapMetadataHandler.cs


示例6: Execute

        public override async Task Execute(string[] parameters, IResponse response)
        {
            string sourceRepo;
            string issueNumberString;
            if (!RepoParser.ParseRepoAndIssueNumber(parameters[1], out sourceRepo, out issueNumberString))
            {
                await response.Send($"I could not parse the source repository and issue number from '{parameters[1]}'. Are you using the correct syntax?");
                return;
            }

            string targetRepo;
            if (!RepoParser.ParseRepo(parameters[2], out targetRepo))
            {
                await response.Send($"I could not parse the target repository from '{parameters[2]}'. Are you using the correct syntax?");
                return;
            }

            int issueNumber;
            if (!int.TryParse(issueNumberString, out issueNumber))
            {
                await response.Send("Issue number should be a valid number dude!");
                return;
            }

            var owner = "Particular";

            await response.Send($"Copying issue https://github.com/{owner}/{sourceRepo}/issues/{issueNumber}").IgnoreWaitContext();

            var newIssue = await IssueUtility.Transfer(owner, sourceRepo, issueNumber, owner, targetRepo, false).IgnoreWaitContext();

            await response.Send($"Issue copied to https://github.com/{owner}/{targetRepo}/issues/{newIssue.Number}").IgnoreWaitContext();
        }
开发者ID:adamralph,项目名称:PBot,代码行数:32,代码来源:CopyIssue.cs


示例7: Assert

        public void Assert(IResponse response)
        {
            // when there are no assertions it is a success
            bool success = (this.assertions.Count == 0);

            // when the response was timedout, there is no data to test/assert
            if (!response.IsTimedOut())
            {
                foreach (AbstractAssertion assertion in this.assertions)
                {
                    success = assertion.Assert(response);
                    LOG.DebugFormat("Assert: {0} result: {1}", assertion.GetType().Name, success);

                    if (!success)
                    {
                        break;
                    }
                }

            }

            // record results
            this.result.Executed = true;
            this.result.ExecutionTime = response.GetExecutionTime();
            this.result.Success = success;
            this.result.TimedOut = response.IsTimedOut();
            this.result.StatusCode = response.GetStatusCode();
            this.result.StatusDescription = response.GetStatusDescription();
            this.result.ResponseText = response.GetResponseText();
        }
开发者ID:Letractively,项目名称:webmvctest,代码行数:30,代码来源:Function.cs


示例8: ProcessRequest

        /// <summary>
        /// This is called by the hosting environment via CatchAll usually for content pages.
        /// </summary>
        public override void ProcessRequest(IRequest httpReq, IResponse httpRes, string operationName)
        {
            httpRes.ContentType = MimeTypes.Html;

            ResolveAndExecuteRazorPage(httpReq, httpRes, null);
            httpRes.EndRequest(skipHeaders: true);
        }
开发者ID:0815sugo,项目名称:ServiceStack,代码行数:10,代码来源:RazorPageResolver.cs


示例9: Respond

 public void Respond(IRequest request, IResponse response)
 {
     response.StatusCode = HttpStatusCode.NotFound;
     response.StatusMessage = "Resource not found";
     response.Output.WriteLine("<h1>404: The resource <i>{0}</i> could not be found.</h1>",
                               request.VirtualPath);
 }
开发者ID:sergiopereira,项目名称:juicy,代码行数:7,代码来源:ResourceNotFoundHandler.cs


示例10: Results

        /// <summary>
        /// Handles rendering a previous MiniProfiler session, identified by its "?id=GUID" on the query.
        /// </summary>
        private static string Results(IRequest httpReq, IResponse httpRes)
        {
            // this guid is the MiniProfiler.Id property
            var id = new Guid();
            if (!Guid.TryParse(httpReq.QueryString["id"], out id))
            {
                return NotFound(httpRes, "text/plain", "No Guid id specified on the query string");
            }

            // load profiler
            var profiler = Profiler.Settings.Storage.Load(id);
            if (profiler == null)
            {
                return NotFound(httpRes, "text/plain", "No MiniProfiler results found with Id=" + id.ToString());
            }

            // ensure that callers have access to these results
            var authorize = Profiler.Settings.Results_Authorize;
            if (authorize != null && !authorize(httpReq, profiler))
            {
                httpRes.StatusCode = 401;
                httpRes.ContentType = "text/plain";
                return "Unauthorized";
            }

            // Only manage full page
            return ResultsFullPage(httpRes, profiler);
        }
开发者ID:Dams33,项目名称:Servicestack-SelfHost-Profiler,代码行数:31,代码来源:SelfhostProfilerHandler.cs


示例11: RequestFilter

        /// <summary>
        /// The request filter is executed before the service.
        /// </summary>
        /// <param name="request">The http request wrapper</param>
        /// <param name="response">The http response wrapper</param>
        /// <param name="requestDto">The request DTO</param>
        public void RequestFilter(IRequest request, IResponse response, object requestDto)
        {
            var serviceRequest = new ServiceStackServiceRequest(request);
            
            //This code is executed before the service
            var auth = AuthorizationContext.GetAuthorizationInfo(serviceRequest);

            if (auth != null)
            {
                User user = null;

                if (!string.IsNullOrWhiteSpace(auth.UserId))
                {
                    var userId = auth.UserId;

                    user = UserManager.GetUserById(userId);
                }

                string deviceId = auth.DeviceId;
                string device = auth.Device;
                string client = auth.Client;
                string version = auth.Version;

                if (!string.IsNullOrEmpty(client) && !string.IsNullOrEmpty(deviceId) && !string.IsNullOrEmpty(device) && !string.IsNullOrEmpty(version))
                {
                    var remoteEndPoint = request.RemoteIp;

                    SessionManager.LogSessionActivity(client, version, deviceId, device, remoteEndPoint, user);
                }
            }
        }
开发者ID:jabbera,项目名称:MediaBrowser,代码行数:37,代码来源:LoggedAttribute.cs


示例12: HostContext

        public HostContext(IRequest request, IResponse response)
        {
            Request = request;
            Response = response;

            Environment = new Dictionary<string, object>();
        }
开发者ID:Choulla-Naresh8264,项目名称:SignalR,代码行数:7,代码来源:HostContext.cs


示例13: GetResponseText

        public static string GetResponseText(IResponse response)
        {
            StringBuilder builder = new StringBuilder();

            // Status
            builder.AppendFormat("Status: {0}\n", response.Status);

            // Headers
            foreach (KeyValuePair<string,IEnumerable<string>> header in response.Headers)
                foreach (string value in header.Value)
                builder.AppendFormat("{0}: {1}\n", header.Key, value);

            builder.Append("\n");

            // Body ... just supports a string body for now ... next up: FileInfo support?
            foreach (object bodyPart in response.GetBody())
                if (bodyPart is string)
                    builder.Append(bodyPart as string);
                else if (bodyPart is byte[])
                    throw new NotImplementedException("TODO test CGI byte[] body output"); //builder.Append(Encoding.UTF8.GetString(bodyPart)); // assume UTF8 encoding for now ...
                else if (bodyPart is ArraySegment<byte>)
                    throw new NotImplementedException("TODO test CGI ArraySegment<byte> body output");
                else if (bodyPart is FileInfo)
                    throw new NotImplementedException("TODO test CGI FileInfo body output");
                else
                    throw new FormatException("Unknown object returned by IResponse.GetBody(): " + bodyPart.GetType().Name);

            return builder.ToString();
        }
开发者ID:remitaylor,项目名称:knack,代码行数:29,代码来源:Cgi.cs


示例14: ProcessRequest

        public override void ProcessRequest(IRequest httpReq, IResponse httpRes, string operationName)
        {
            if (HostContext.ApplyCustomHandlerRequestFilters(httpReq, httpRes))
                return;

            Action(httpReq, httpRes);
        }
开发者ID:jrmitch120,项目名称:ServiceStack,代码行数:7,代码来源:CustomActionHandler.cs


示例15: ProcessResponseAsync

 protected override async Task ProcessResponseAsync(IResponse response)
 {
     var context = new BrowsingContext(_parentDocument.Context, Sandboxes.None);
     var options = new CreateDocumentOptions(response, _configuration, _parentDocument);
     var factory = _configuration.GetFactory<IDocumentFactory>();
     ChildDocument = await factory.CreateAsync(context, options, CancellationToken.None).ConfigureAwait(false);
 }
开发者ID:Wojdav,项目名称:AngleSharp,代码行数:7,代码来源:DocumentRequestProcessor.cs


示例16: HostContext

 public HostContext(IRequest request, IResponse response, IPrincipal user)
 {
     Request = request;
     Response = response;
     User = user;
     Items = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
 }
开发者ID:ninjaAB,项目名称:SignalR,代码行数:7,代码来源:HostContext.cs


示例17: Execute

        public override async Task Execute(string[] parameters, IResponse response)
        {
            var username = parameters[1];
            var repoName = parameters[3];

            var activeRepositories = Brain.Get<AvailableRepositories>();

            var repo = activeRepositories.SingleOrDefault(r => r.Name == repoName);

            if (repo == null)
            {
                await response.Send("Repository not found, please add it using: mmbot add repo " + repoName).IgnoreWaitContext();
                return;
            }

            if (username.ToLower() == "my self")
            {
                repo.Caretaker = CurrentUser.Name;
            }
            else
            {
                repo.Caretaker = username;
            }

            Brain.Set(activeRepositories);

            await response.Send(username + " is now caretaker for " + repo.Name);
        }
开发者ID:adamralph,项目名称:PBot,代码行数:28,代码来源:RegisterCaretaker.cs


示例18: Execute

        public override void Execute(IRequest req, IResponse res, object requestDto)
        {
            if (HostContext.HasValidAuthSecret(req))
                return;

            base.Execute(req, res, requestDto); //first check if session is authenticated
            if (res.IsClosed) return; //AuthenticateAttribute already closed the request (ie auth failed)

            var session = req.GetSession();

            var authRepo = HostContext.AppHost.GetAuthRepository(req);
            using (authRepo as IDisposable)
            {
                if (session != null && session.HasRole(RoleNames.Admin, authRepo))
                    return;

                if (HasAnyPermissions(req, session, authRepo)) return;
            }

            if (DoHtmlRedirectIfConfigured(req, res)) return;

            res.StatusCode = (int)HttpStatusCode.Forbidden;
            res.StatusDescription = ErrorMessages.InvalidPermission;
            res.EndRequest();
        }
开发者ID:AVee,项目名称:ServiceStack,代码行数:25,代码来源:RequiresAnyPermission.cs


示例19: Serialize

        public virtual int Serialize(IResponse response, byte[] buffer)
        {
            var stream = new MemoryStream(buffer);
            var writer = new StreamWriter(stream, Encoding.ASCII);
            writer.Write(response.SipVersion);
            writer.Write(" ");
            writer.Write((int) response.StatusCode);
            writer.Write(" ");
            writer.WriteLine(response.ReasonPhrase);

            WriteHeader(writer, "To", response.To);
            WriteHeader(writer, "From", response.From);
            WriteHeader(writer, "Contact", response.Contact);
            WriteHeader(writer, "Via", response.Via);
            WriteHeader(writer, "CSeq", response.CSeq);
            //WriteHeader(writer, "Call-Id", response.CallId);
            foreach (var header in response.Headers)
                WriteHeader(writer, header.Key, header.Value.ToString());
            if (response.Body != null && response.Body.Length > 0)
                WriteHeader(writer, "Content-Length", response.Body.Length);
            else
                WriteHeader(writer, "Content-Length", "0");
            writer.WriteLine();

            if (response.Body != null)
            {
                var ms = (MemoryStream) response.Body;
                ms.WriteTo(stream);
            }

            writer.Flush();

            string temp = Encoding.ASCII.GetString(buffer, 0, (int) stream.Length);
            return (int) stream.Position;
        }
开发者ID:jgauffin,项目名称:SipSharp,代码行数:35,代码来源:MessageSerializer.cs


示例20: RequestFilter

        public static void RequestFilter(IRequest req, IResponse res, object requestDto)
        {
            var validator = ValidatorCache.GetValidator(req, requestDto.GetType());
            if (validator == null) return;

            var validatorWithHttpRequest = validator as IRequiresRequest;
            if (validatorWithHttpRequest != null)
                validatorWithHttpRequest.Request = req;

            var ruleSet = req.Verb;
            var validationResult = validator.Validate(
                new ValidationContext(requestDto, null, new MultiRuleSetValidatorSelector(ruleSet)));

            if (validationResult.IsValid) return;

            var errorResponse = DtoUtils.CreateErrorResponse(
                requestDto, validationResult.ToErrorResult());

            var validationFeature = HostContext.GetPlugin<ValidationFeature>();
            if (validationFeature != null && validationFeature.ErrorResponseFilter != null)
            {
                errorResponse = validationFeature.ErrorResponseFilter(validationResult, errorResponse);
            }

            res.WriteToResponse(req, errorResponse);
        }
开发者ID:GDBSD,项目名称:ServiceStack,代码行数:26,代码来源:ValidationFilters.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# IRestClient类代码示例发布时间:2022-05-24
下一篇:
C# IResourceService类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap