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

C# Http.HttpResponse类代码示例

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

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



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

示例1: WriteFileAsync

        /// <inheritdoc />
        protected override Task WriteFileAsync(HttpResponse response, CancellationToken cancellation)
        {
            var bufferingFeature = response.HttpContext.Features.Get<IHttpBufferingFeature>();
            bufferingFeature?.DisableResponseBuffering();

            return response.Body.WriteAsync(FileContents, 0, FileContents.Length, cancellation);
        }
开发者ID:4myBenefits,项目名称:Mvc,代码行数:8,代码来源:FileContentResult.cs


示例2: WriteFileAsync

        /// <inheritdoc />
        protected override async Task WriteFileAsync(HttpResponse response)
        {
            if (!Path.IsPathRooted(FileName))
            {
                throw new NotSupportedException(Resources.FormatFileResult_PathNotRooted(FileName));
            }

            var sendFile = response.HttpContext.Features.Get<IHttpSendFileFeature>();
            if (sendFile != null)
            {
                await sendFile.SendFileAsync(
                    FileName,
                    offset: 0,
                    length: null,
                    cancellation: default(CancellationToken));
            }
            else
            {
                var fileStream = GetFileStream(FileName);

                using (fileStream)
                {
                    await fileStream.CopyToAsync(response.Body, DefaultBufferSize);
                }
            }
        }
开发者ID:phinq19,项目名称:git_example,代码行数:27,代码来源:PhysicalFileResult.cs


示例3: ToHttpResponse

        internal static HttpResponsePacket ToHttpResponse(HttpResponse response, ServiceMessage msg)
        {
            var rsp = new HttpResponsePacket();

            foreach (var hdr in response.Headers)
            {
                // TODO: Fix adding response headers
                //AddHttpHeader(hdr);
            }

            //TODO: Decide if to read mostly from ServiceMessage or from response.

            //rsp.Version = response.... //TODO: Add a default version here
            rsp.StatusCode = (int)response.StatusCode;
            rsp.StatusDescription = ((IHttpResponseFeature)msg).ReasonPhrase;

            if (response.Body != null)
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    response.Body.Position = 0;
                    response.Body.CopyTo(ms);
                    rsp.Content = ms.ToArray();
                }
            }

            return rsp;
        }
开发者ID:BrisWhite,项目名称:RestBus,代码行数:28,代码来源:MessageHelpers.cs


示例4: WriteFileAsync

        /// <inheritdoc />
        protected override Task WriteFileAsync(HttpResponse response)
        {
            var bufferingFeature = response.HttpContext.Features.Get<IHttpBufferingFeature>();
            bufferingFeature?.DisableResponseBuffering();

            return response.Body.WriteAsync(FileContents, offset: 0, count: FileContents.Length);
        }
开发者ID:phinq19,项目名称:git_example,代码行数:8,代码来源:FileContentResult.cs


示例5: WriteFileAsync

        /// <inheritdoc />
        protected override async Task WriteFileAsync(HttpResponse response, CancellationToken cancellation)
        {
            if (!Path.IsPathRooted(FileName))
            {
                throw new FileNotFoundException(Resources.FormatFileResult_InvalidPath(FileName), FileName);
            }

            var sendFile = response.HttpContext.Features.Get<IHttpSendFileFeature>();
            if (sendFile != null)
            {
                await sendFile.SendFileAsync(
                    FileName,
                    offset: 0,
                    length: null,
                    cancellation: cancellation);

                return;
            }
            else
            {
                var fileStream = GetFileStream(FileName);

                using (fileStream)
                {
                    await fileStream.CopyToAsync(response.Body, DefaultBufferSize, cancellation);
                }

                return;
            }
        }
开发者ID:4myBenefits,项目名称:Mvc,代码行数:31,代码来源:PhysicalFileProviderResult.cs


示例6: WriteFileAsync

        /// <inheritdoc />
        protected async override Task WriteFileAsync(HttpResponse response, CancellationToken cancellation)
        {
            var outputStream = response.Body;

            using (FileStream)
            {
                await FileStream.CopyToAsync(outputStream, BufferSize, cancellation);
            }
        }
开发者ID:AndersBillLinden,项目名称:Mvc,代码行数:10,代码来源:FileStreamResult.cs


示例7: SetCacheHeaders

 private void SetCacheHeaders(HttpResponse response)
 {
     if (_options.CacheLength != null)
     {
         var expires = DateTime.Now.AddSeconds(_options.CacheLength.TotalSeconds);
         response.Headers.SetCommaSeparatedValues("Cache-Control", "public", $"max-age={_options.CacheLength.TotalSeconds}");
         response.Headers.Set("Expires", expires.ToUniversalTime().ToString("R"));
     }
 }
开发者ID:luckycadow,项目名称:beerfish,代码行数:9,代码来源:AssetMiddleware.cs


示例8: RespondWithSwaggerJson

        private void RespondWithSwaggerJson(HttpResponse response, SwaggerDocument swagger)
        {
            response.StatusCode = 200;
            response.ContentType = "application/json";

            using (var writer = new StreamWriter(response.Body))
            {
                _swaggerSerializer.Serialize(writer, swagger);
            }
        }
开发者ID:serkanpektas,项目名称:Ahoy,代码行数:10,代码来源:SwaggerDocsMIddleware.cs


示例9: SerializeResponseObject

 private void SerializeResponseObject(HttpResponse response, object value)
 {
     using (var writer = new StreamWriter(response.Body))
     {
         using (var jsonWriter = new JsonTextWriter(writer))
         {
             jsonWriter.CloseOutput = false;
             var jsonSerializer = JsonSerializer.Create(/*TODO: SerializerSettings*/);
             jsonSerializer.Serialize(jsonWriter, value);
         }
     }
 }
开发者ID:robbert229,项目名称:omnisharp-roslyn,代码行数:12,代码来源:StatusMiddleware.cs


示例10: WriteFileAsync

        /// <inheritdoc />
        protected async override Task WriteFileAsync(HttpResponse response, CancellationToken cancellation)
        {
            var outputStream = response.Body;

            using (FileStream)
            {
                var bufferingFeature = response.HttpContext.Features.Get<IHttpBufferingFeature>();
                bufferingFeature?.DisableResponseBuffering();

                await FileStream.CopyToAsync(outputStream, BufferSize, cancellation);
            }
        }
开发者ID:4myBenefits,项目名称:Mvc,代码行数:13,代码来源:FileStreamResult.cs


示例11: WriteResponseBodyAsync

 internal static Task WriteResponseBodyAsync(HttpResponse response, string uid, DateTimeOffset? datetime, TimeSpan? duration, string summary, string description, string location) {
     return response.WriteAsync(
         "BEGIN:VCALENDAR\r\n" +
         "VERSION:2.0\r\n" +
         "BEGIN:VEVENT\r\n" +
         "UID:" + uid + "\r\n" +
         "DTSTART:" + datetime?.ToString(DateTimeFormat) + "\r\n" +
         "DTEND:" + datetime?.Add(duration ?? TimeSpan.Zero).ToString(DateTimeFormat) + "\r\n" +
         "SUMMARY:" + summary + "\r\n" +
         "DESCRIPTION:" + description + "\r\n" +
         "LOCATION:" + location +
         "END:VEVENT\r\n" +
         "END:VCALENDAR\r\n");
 }
开发者ID:migrap,项目名称:Migrap.AspNet.Mvc.Formatters.iCalendar,代码行数:14,代码来源:iCalendarOutputFormatter.cs


示例12: AddLocationHeaderToMapping

        public static void AddLocationHeaderToMapping(
            HttpResponse response,
            IDictionary<string, string> contentIdToLocationMapping,
            string contentId)
        {
            //Contract.Assert(response != null);
            //Contract.Assert(contentIdToLocationMapping != null);
            //Contract.Assert(contentId != null);

            //if (response.Headers.Location != null)
            //{
            //    contentIdToLocationMapping.Add(contentId, response.Headers.Location.AbsoluteUri);
            //}
            throw new NotImplementedException("AddLocationHeaderToMapping");
        }
开发者ID:akrisiun,项目名称:WebApi,代码行数:15,代码来源:ContentIdHelpers.cs


示例13: WriteOutput

		public static async Task WriteOutput(HttpResponse Response, string Title, Head.Tag[] HeadTags, string Body) {
			var sb = new StringBuilder();
			sb.Append("<!DOCTYPE html><head><meta charset=\"utf-8\">");
			if (Title != null) {
				sb.Append("<title>" + Title + "</title>");
			}
			if (HeadTags != null) {
				foreach (var a in HeadTags) {
					sb.Append(a.Output());
				}
			}
			sb.Append("</head><body>");
			sb.Append(Body);
			sb.Append("</body></html>");
			await Response.WriteAsync(sb.ToString());
		}
开发者ID:matthewhancock,项目名称:plasticbagfreeportsmouth,代码行数:16,代码来源:Html.cs


示例14: WriteFileAsync

        /// <inheritdoc />
        protected override Task WriteFileAsync(HttpResponse response, CancellationToken cancellation)
        {
            var fileProvider = GetFileProvider(response.HttpContext.RequestServices);

            var resolveFilePathResult = ResolveFilePath(fileProvider);

            if (resolveFilePathResult.PhysicalFilePath != null)
            {
                return CopyPhysicalFileToResponseAsync(response, resolveFilePathResult.PhysicalFilePath, cancellation);
            }
            else
            {
                // Example: An embedded resource
                var sourceStream = resolveFilePathResult.FileInfo.CreateReadStream();
                return CopyStreamToResponseAsync(sourceStream, response, cancellation);
            }
        }
开发者ID:njannink,项目名称:sonarlint-vs,代码行数:18,代码来源:FilePathResult.cs


示例15: CreateMockActionContext

        private static ActionContext CreateMockActionContext(
                                                             HttpResponse response = null,
                                                             string requestAcceptHeader = "application/*",
                                                             string requestContentType = "application/json",
                                                             string requestAcceptCharsetHeader = "",
                                                             bool respectBrowserAcceptHeader = false)
        {
            var httpContext = new Mock<HttpContext>();
            if (response != null)
            {
                httpContext.Setup(o => o.Response).Returns(response);
            }

            var content = "{name: 'Person Name', Age: 'not-an-age'}";
            var contentBytes = Encoding.UTF8.GetBytes(content);

            var request = new DefaultHttpContext().Request;
            request.Headers["Accept-Charset"] = requestAcceptCharsetHeader;
            request.Headers["Accept"] = requestAcceptHeader;
            request.ContentType = requestContentType;
            request.Body = new MemoryStream(contentBytes);

            httpContext.Setup(o => o.Request).Returns(request);
            httpContext.Setup(o => o.RequestServices).Returns(GetServiceProvider());
            var optionsAccessor = new MockMvcOptionsAccessor();
            optionsAccessor.Options.OutputFormatters.Add(new StringOutputFormatter());
            optionsAccessor.Options.OutputFormatters.Add(new JsonOutputFormatter());
            optionsAccessor.Options.RespectBrowserAcceptHeader = respectBrowserAcceptHeader;
            var mockContextAccessor = new Mock<IScopedInstance<ActionBindingContext>>();
            mockContextAccessor
                .SetupGet(o => o.Value)
                .Returns(new ActionBindingContext()
                {
                    OutputFormatters = optionsAccessor.Options.OutputFormatters
                });

            httpContext.Setup(o => o.RequestServices.GetService(typeof(IScopedInstance<ActionBindingContext>)))
                       .Returns(mockContextAccessor.Object);
            httpContext.Setup(o => o.RequestServices.GetService(typeof(IOptions<MvcOptions>)))
                .Returns(optionsAccessor);
            httpContext.Setup(o => o.RequestServices.GetService(typeof(ILogger<ObjectResult>)))
                .Returns(new Mock<ILogger<ObjectResult>>().Object);

            return new ActionContext(httpContext.Object, new RouteData(), new ActionDescriptor());
        }
开发者ID:RehanSaeed,项目名称:Mvc,代码行数:45,代码来源:HttpNotFoundObjectResultTest.cs


示例16: WriteFileAsync

        /// <inheritdoc />
        protected override async Task WriteFileAsync(HttpResponse response, CancellationToken cancellation)
        {
            var fileProvider = GetFileProvider(response.HttpContext.RequestServices);

            var normalizedPath = FileName;
            if (normalizedPath.StartsWith("~"))
            {
                normalizedPath = normalizedPath.Substring(1);
            }

            var fileInfo = fileProvider.GetFileInfo(normalizedPath);
            if (fileInfo.Exists)
            {
                var physicalPath = fileInfo.PhysicalPath;
                var sendFile = response.HttpContext.Features.Get<IHttpSendFileFeature>();
                if (sendFile != null && !string.IsNullOrEmpty(physicalPath))
                {
                    await sendFile.SendFileAsync(
                        physicalPath,
                        offset: 0,
                        length: null,
                        cancellation: cancellation);

                    return;
                }
                else
                {
                    var fileStream = GetFileStream(fileInfo);
                    using (fileStream)
                    {
                        await fileStream.CopyToAsync(response.Body, DefaultBufferSize, cancellation);
                    }

                    return;
                }
            }

            throw new FileNotFoundException(
                Resources.FormatFileResult_InvalidPath(FileName), FileName);
        }
开发者ID:4myBenefits,项目名称:Mvc,代码行数:41,代码来源:VirtualFileProviderResult.cs


示例17: CreateMockActionContext

        private static ActionContext CreateMockActionContext(
                                                             HttpResponse response = null,
                                                             string requestAcceptHeader = "application/*",
                                                             string requestContentType = "application/json",
                                                             string requestAcceptCharsetHeader = "",
                                                             bool respectBrowserAcceptHeader = false)
        {
            var formatters = new IOutputFormatter[] { new StringOutputFormatter(), new JsonOutputFormatter() };
            var httpContext = new Mock<HttpContext>();
            if (response != null)
            {
                httpContext.Setup(o => o.Response).Returns(response);
            }

            var content = "{name: 'Person Name', Age: 'not-an-age'}";
            var contentBytes = Encoding.UTF8.GetBytes(content);

            var request = new DefaultHttpContext().Request;
            request.Headers["Accept-Charset"] = requestAcceptCharsetHeader;
            request.Headers["Accept"] = requestAcceptHeader;
            request.ContentType = requestContentType;
            request.Body = new MemoryStream(contentBytes);

            httpContext.Setup(o => o.Request).Returns(request);
            httpContext.Setup(o => o.RequestServices).Returns(GetServiceProvider());
            httpContext.Setup(o => o.RequestServices.GetService(typeof(IOutputFormattersProvider)))
                       .Returns(new TestOutputFormatterProvider(formatters));

            var options = new Mock<IOptions<MvcOptions>>();
            options.SetupGet(o => o.Options)
                       .Returns(new MvcOptions()
                       {
                           RespectBrowserAcceptHeader = respectBrowserAcceptHeader
                       });
            httpContext.Setup(o => o.RequestServices.GetService(typeof(IOptions<MvcOptions>)))
                       .Returns(options.Object);

            return new ActionContext(httpContext.Object, new RouteData(), new ActionDescriptor());
        }
开发者ID:AndersBillLinden,项目名称:Mvc,代码行数:39,代码来源:HttpNotFoundObjectResultTest.cs


示例18: GetSession

 public IBookshelfSession GetSession(HttpResponse response,string userName, string clientId,string userEmail)
 {
     var hashCode = GetSessionHashCode(userName, clientId);
     IBookshelfSession session;
     var sessionFound = _sessions.TryGetValue(hashCode, out session);
     if (sessionFound && session.IsExpired())
     {
         //remove expired session - IsExpired removes expired session by it's call
         //esnure session not found workflow is going to be applied
         sessionFound = false;
     }
     //if there is no such session in storage, or there is but it's expired - create new one
     if (!sessionFound)
     {
         var userInfo = new InSessionUserInfo { UserEmail = userEmail, UserClientId = clientId, UserName = userName };
         session = CreateServerSession(hashCode, userInfo,response);
         //check if there is proper active device alreadybeen created
         if (_cache.Get(userName) != null)
         {
             Dictionary<string, IBookshelfSession> deviceSessions =
                 (Dictionary<string, IBookshelfSession>) _cache.Get(userName);
             if (!deviceSessions.ContainsKey(clientId))
             {
                 deviceSessions.Add(clientId, session);
             }
         }
         else
         {
             _cache.Set(userName, new Dictionary<string, IBookshelfSession>
             {
                 {
                     clientId, session
                 }
             });
         }
     }
     return session;
 }
开发者ID:anton-gorbikov,项目名称:Bookshelf,代码行数:38,代码来源:ServerSessionManager.cs


示例19: CreateMockActionContext

        private static ActionContext CreateMockActionContext(
            IEnumerable<IOutputFormatter> outputFormatters,
            HttpResponse response = null,
            string requestAcceptHeader = "application/*",
            string requestContentType = "application/json",
            string requestAcceptCharsetHeader = "",
            bool respectBrowserAcceptHeader = false,
            bool setupActionBindingContext = true)
        {
            var httpContext = new Mock<HttpContext>();
            if (response != null)
            {
                httpContext.Setup(o => o.Response).Returns(response);
            }

            var content = "{name: 'Person Name', Age: 'not-an-age'}";
            var contentBytes = Encoding.UTF8.GetBytes(content);

            var request = new DefaultHttpContext().Request;
            request.Headers["Accept-Charset"] = requestAcceptCharsetHeader;
            request.Headers["Accept"] = requestAcceptHeader;
            request.ContentType = requestContentType;
            request.Body = new MemoryStream(contentBytes);

            httpContext.Setup(o => o.Request).Returns(request);
            httpContext.Setup(o => o.RequestServices).Returns(GetServiceProvider());

            var optionsAccessor = new MockMvcOptionsAccessor();
            foreach (var formatter in outputFormatters)
            {
                optionsAccessor.Options.OutputFormatters.Add(formatter);
            }

            optionsAccessor.Options.RespectBrowserAcceptHeader = respectBrowserAcceptHeader;
            httpContext.Setup(o => o.RequestServices.GetService(typeof(IOptions<MvcOptions>)))
                .Returns(optionsAccessor);
            httpContext.Setup(o => o.RequestServices.GetService(typeof(ILogger<ObjectResult>)))
                .Returns(new Mock<ILogger<ObjectResult>>().Object);

            ActionBindingContext actionBindingContext = null;
            if (setupActionBindingContext)
            {
                actionBindingContext = new ActionBindingContext { OutputFormatters = outputFormatters.ToList() };
            }
            
            httpContext.Setup(o => o.RequestServices.GetService(typeof(IActionBindingContextAccessor)))
                    .Returns(new ActionBindingContextAccessor() { ActionBindingContext = actionBindingContext });

            return new ActionContext(httpContext.Object, new RouteData(), new ActionDescriptor());
        }
开发者ID:ryanbrandenburg,项目名称:Mvc,代码行数:50,代码来源:ObjectResultTests.cs


示例20: WriteOtherSettingsAsync

 public async Task WriteOtherSettingsAsync(HttpResponse response)
 {
     await response.WriteAsync(
         $"OtherSettings Strings: {string.Join(", ", _otherSettings.Strings)}<br>" +
         $"OtherSettings Numbers: {string.Join(", ", _otherSettings.Numbers)}");
 }
开发者ID:jeffogata,项目名称:aspnet-configuration-04-cli,代码行数:6,代码来源:MyClass.cs



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
C# Internal.DefaultHttpContext类代码示例发布时间:2022-05-26
下一篇:
C# Http.HttpRequest类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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