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


C# IResponse.AddHeader方法代码示例

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


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

示例1: ProcessRequest

        /// <summary>
        /// Non ASP.NET requests
        /// </summary>
        /// <param name="request"></param>
        /// <param name="response"></param>
        /// <param name="operationName"></param>
        public override void ProcessRequest(IRequest request, IResponse response, string operationName)
        {
            if (string.IsNullOrEmpty(RelativeUrl) && string.IsNullOrEmpty(AbsoluteUrl))
                throw new ArgumentException("RelativeUrl and AbsoluteUrl is Required");

            if (!string.IsNullOrEmpty(AbsoluteUrl))
            {
                response.StatusCode = (int)StatusCode;
                response.AddHeader(HttpHeaders.Location, this.AbsoluteUrl);
            }
            else
            {
                var absoluteUrl = request.GetApplicationUrl();
                if (!string.IsNullOrEmpty(RelativeUrl))
                {
                    if (this.RelativeUrl.StartsWith("/"))
                        absoluteUrl = absoluteUrl.CombineWith(this.RelativeUrl);
                    else if (this.RelativeUrl.StartsWith("~/"))
                        absoluteUrl = absoluteUrl.CombineWith(this.RelativeUrl.Replace("~/", ""));
                    else
                        absoluteUrl = request.AbsoluteUri.CombineWith(this.RelativeUrl);
                }
                response.StatusCode = (int)StatusCode;
                response.AddHeader(HttpHeaders.Location, absoluteUrl);
            }

            response.EndHttpHandlerRequest(skipClose: true);
        }
开发者ID:ServiceStack,项目名称:ServiceStack,代码行数:34,代码来源:RedirectHttpHandler.cs

示例2: OSHttpResponse

        public OSHttpResponse(IPipelineHandlerContext context, IRequest request, IResponse response)
        {
            _httpContext = context;
            _httpRequest = request;
            _httpResponse = response;

            _httpResponse.AddHeader("remote_addr", MainServer.Instance.HostName);
            _httpResponse.AddHeader("remote_port", MainServer.Instance.Port.ToString());
        }
开发者ID:nathanmarck,项目名称:Aurora-Sim,代码行数:9,代码来源:OSHttpResponse.cs

示例3: FilterResponse

        /// <summary>
        /// Filters the response.
        /// </summary>
        /// <param name="req">The req.</param>
        /// <param name="res">The res.</param>
        /// <param name="dto">The dto.</param>
        public void FilterResponse(IRequest req, IResponse res, object dto)
        {
            // Try to prevent compatibility view
            res.AddHeader("X-UA-Compatible", "IE=Edge");

            var exception = dto as Exception;

            if (exception != null)
            {
                _logger.ErrorException("Error processing request for {0}", exception, req.RawUrl);

                if (!string.IsNullOrEmpty(exception.Message))
                {
                    var error = exception.Message.Replace(Environment.NewLine, " ");
                    error = RemoveControlCharacters(error);

                    res.AddHeader("X-Application-Error-Code", error);
                }
            }

            if (dto is CompressedResult)
            {
                // Per Google PageSpeed
                // This instructs the proxies to cache two versions of the resource: one compressed, and one uncompressed. 
                // The correct version of the resource is delivered based on the client request header. 
                // This is a good choice for applications that are singly homed and depend on public proxies for user locality.                        
                res.AddHeader("Vary", "Accept-Encoding");
            }

            var hasOptions = dto as IHasOptions;

            if (hasOptions != null)
            {
                // Content length has to be explicitly set on on HttpListenerResponse or it won't be happy
                string contentLength;

                if (hasOptions.Options.TryGetValue("Content-Length", out contentLength) && !string.IsNullOrEmpty(contentLength))
                {
                    var length = long.Parse(contentLength, UsCulture);

                    if (length > 0)
                    {
                        var response = (HttpListenerResponse)res.OriginalResponse;

                        response.ContentLength64 = length;
                       
                        // Disable chunked encoding. Technically this is only needed when using Content-Range, but
                        // anytime we know the content length there's no need for it
                        response.SendChunked = false;
                    }
                }
            }
        }
开发者ID:Rycius,项目名称:MediaBrowser,代码行数:59,代码来源:ResponseFilter.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: Execute

        public override void Execute(IRequest req, IResponse res, object requestDto)
        {
            if (StatusCode != null)
            {
                res.StatusCode = StatusCode.Value;
            }

            if (StatusDescription != null)
            {
                res.StatusDescription = StatusDescription;
            }

            if (!string.IsNullOrEmpty(Name) && !string.IsNullOrEmpty(Value))
            {
                if (Name.EqualsIgnoreCase(HttpHeaders.ContentType))
                {
                    req.ResponseContentType = Value; //Looked at in WriteRespone
                }
                else if (Name == "DefaultContentType")
                {
                    if (!req.HasExplicitResponseContentType)
                    {
                        req.ResponseContentType = Value; //Looked at in WriteRespone
                    }
                }
                else
                {
                    res.AddHeader(Name, Value);
                }
            }
        }
开发者ID:vebin,项目名称:soa,代码行数:31,代码来源:AddHeaderAttribute.cs

示例6: CreateChallenge

        /// <summary>
        /// Create a WWW-Authenticate header
        /// </summary>
        public void CreateChallenge(IRequest request, IResponse response)
        {
            var nonce = GetCurrentNonce();

            var challenge = new StringBuilder("Digest realm=\"");
            challenge.Append(_realmRepository.GetRealm(request));
            challenge.Append("\"");
            challenge.Append(", nonce=\"");
            challenge.Append(nonce);
            challenge.Append("\"");
            challenge.Append(", opaque=\"" + Guid.NewGuid().ToString().Replace("-", string.Empty) + "\"");

            /* Disable the stale mechanism
             * We should really generate the responses directly in these classes.
            challenge.Append(", stale=");
            challenge.Append((bool)options[0] ? "true" : "false");
            challenge.Append("false");
             * */

            challenge.Append(", algorithm=MD5");
            challenge.Append(", qop=auth");


            response.AddHeader("WWW-Authenticate", challenge.ToString());
        }
开发者ID:nathanmarck,项目名称:Aurora-Sim,代码行数:28,代码来源:DigestAuthenticator.cs

示例7: ProcessRequest

        /// <summary>
        /// Non ASP.NET requests
        /// </summary>
        public override void ProcessRequest(IRequest request, IResponse response, string operationName)
        {
            var defaultUrl = HostContext.Config.ServiceEndpointsMetadataConfig.DefaultMetadataUri;

            if (request.PathInfo == "/")
            {
                var relativeUrl = defaultUrl.Substring(defaultUrl.IndexOf('/'));
                var absoluteUrl = request.RawUrl.TrimEnd('/') + relativeUrl;
                response.StatusCode = (int)HttpStatusCode.Redirect;
                response.AddHeader(HttpHeaders.Location, absoluteUrl);
            }
            else
            {
                response.StatusCode = (int)HttpStatusCode.Redirect;
                response.AddHeader(HttpHeaders.Location, defaultUrl);
            }
        }
开发者ID:softwx,项目名称:ServiceStack,代码行数:20,代码来源:IndexPageHttpHandler.cs

示例8: Serve

        public void Serve(string path, IRequest request, IResponse response)
        {
            if (request.Uri.Segments.Any(p => p == ".."))
                throw new HttpForbiddenException("Disallowed characters in path");
            if (Path.IsPathRooted(path)) path = path.Substring(path.IndexOfAny(new[] { Path.DirectorySeparatorChar, '/', '\\' }) + 1);
            if (!File.Exists(Path.Combine(BaseDirectory, path)))
                throw new HttpNotFoundException("The requested static content was not found.");

            var stream = File.OpenRead(Path.Combine(BaseDirectory, path));
            var extension = Path.GetExtension(path);
            if (extension != null)
                response.ContentType = HttpServer.GetContentTypeForExtension(extension.Substring(1));
            response.AddHeader("Accept-Ranges", "bytes");

            // Handle ranges
            long length = stream.Length;
            if (request.Headers.Any(h => h.Name == "Range"))
            {
                //response.StatusCode = 206; // Breaks things for some unknown reason, quite infuriating
                //response.StatusDescription = "Partial Content";
                var range = request.Headers["Range"].Value;
                var type = range.Remove(range.IndexOf("=", StringComparison.Ordinal));
                if (type != "bytes")
                {
                    response.StatusCode = 400;
                    response.StatusDescription = "Bad Request";
                    return;
                }
                range = range.Substring(range.IndexOf("=", StringComparison.Ordinal) + 1);
                var rangeParts = range.Split('-');
                long start = int.Parse(rangeParts[0]);
                long end;
                if (!long.TryParse(rangeParts[1], out end))
                    end = length;
                length = end - start;
                response.AddHeader("Content-Range", string.Format("bytes {0}-{1}/{2}", start, end, length));
                stream.Seek(start, SeekOrigin.Begin);
            }
            //stream._Length = length;
            response.Body = new MemoryStream();
            stream.CopyTo(response.Body);
            stream.Close();
            response.Body.Seek(0, SeekOrigin.Begin);
        }
开发者ID:headdetect,项目名称:WebSharp,代码行数:44,代码来源:StaticContentHandler.cs

示例9: Execute

        public override void Execute(IRequest req, IResponse res, object requestDto)
        {
            if (StatusCode != null)
            {
                res.StatusCode = StatusCode.Value;
            }

            if (StatusDescription != null)
            {
                res.StatusDescription = StatusDescription;
            }

            if (!string.IsNullOrEmpty(Name) && !string.IsNullOrEmpty(Value))
            {
                if (Name.Equals(HttpHeaders.ContentType, StringComparison.InvariantCultureIgnoreCase))
                {
                    res.ContentType = Value;
                }
                else
                {
                    res.AddHeader(Name, Value);
                }
            }
        }
开发者ID:RyanR100,项目名称:ServiceStack,代码行数:24,代码来源:AddHeaderAttribute.cs

示例10: OnFailedAuthentication

 public override void OnFailedAuthentication(IAuthSession session, IRequest httpReq, IResponse httpRes)
 {
     var digestHelper = new DigestAuthFunctions();
     httpRes.StatusCode = (int) HttpStatusCode.Unauthorized;
     httpRes.AddHeader(
         HttpHeaders.WwwAuthenticate,
         "{0} realm=\"{1}\", nonce=\"{2}\", qop=\"auth\"".Fmt(Provider, AuthRealm, digestHelper.GetNonce(httpReq.UserHostAddress, PrivateKey)));
     httpRes.EndRequest();
 }
开发者ID:jango2015,项目名称:ServiceStack,代码行数:9,代码来源:DigestAuthProvider.cs

示例11: CreateChallenge

 /// <summary>
 /// Create a WWW-Authenticate header
 /// </summary>
 public void CreateChallenge(IRequest httpRequest, IResponse response)
 {
     response.AddHeader("WWW-Authenticate", "Basic realm=\"" + _realm + "\"");
     response.StatusCode = 401;
 }
开发者ID:2594636985,项目名称:griffin.networking,代码行数:8,代码来源:BasicAuthentication.cs

示例12: OnFailedAuthentication

 public override void OnFailedAuthentication(IAuthSession session, IRequest httpReq, IResponse httpRes)
 {
     httpRes.StatusCode = (int)HttpStatusCode.Unauthorized;
     //Needs to be 'Basic ' in order for HttpWebRequest to accept challenge and send NetworkCredentials
     httpRes.AddHeader(HttpHeaders.WwwAuthenticate, $"Basic realm=\"{this.AuthRealm}\"");
     httpRes.EndRequest();
 }
开发者ID:AVee,项目名称:ServiceStack,代码行数:7,代码来源:ApiKeyAuthProvider.cs

示例13: SendJson

        /// <summary>
        /// See interface docs.
        /// </summary>
        /// <param name="response"></param>
        /// <param name="json"></param>
        /// <param name="jsonpCallbackFunction"></param>
        public void SendJson(IResponse response, object json, string jsonpCallbackFunction)
        {
            if(response == null) throw new ArgumentNullException("response");
            if(json == null) throw new ArgumentNullException("json");

            response.AddHeader("Cache-Control", "max-age=0, no-cache, no-store, must-revalidate");

            var type = json.GetType();
            JsonSerialiser serialiser;
            lock(_SyncLock) {
                if(!_JsonSerialiserMap.TryGetValue(type, out serialiser)) {
                    serialiser = new JsonSerialiser();
                    serialiser.Initialise(type);
                    _JsonSerialiserMap.Add(type, serialiser);
                }
            }

            string text;
            using(MemoryStream stream = new MemoryStream()) {
                serialiser.WriteObject(stream, json);
                text = Encoding.UTF8.GetString(stream.ToArray());
            }

            if(!String.IsNullOrEmpty(jsonpCallbackFunction)) text = String.Format("{0}({1})", jsonpCallbackFunction, text);

            SendText(response, text, Encoding.UTF8, MimeType.Json);
        }
开发者ID:cihanozhan,项目名称:virtual-radar-server,代码行数:33,代码来源:Responder.cs

示例14: CacheAndWriteResponse

        private bool CacheAndWriteResponse(CacheInfo cacheInfo, IRequest req, IResponse res, object response)
        {
            var httpResult = response as IHttpResult;
            var dto = httpResult != null ? httpResult.Response : response;
            if (dto == null || dto is IPartialWriter || dto is IStreamWriter)
                return false;

            var expiresIn = cacheInfo.ExpiresIn.GetValueOrDefault(DefaultExpiresIn);
            var cache = cacheInfo.LocalCache ? HostContext.LocalCache : HostContext.Cache;

            var responseBytes = dto as byte[];
            if (responseBytes == null)
            {
                var rawStr = dto as string;
                if (rawStr != null)
                    responseBytes = rawStr.ToUtf8Bytes();
                else
                {
                    var stream = dto as Stream;
                    if (stream != null)
                        responseBytes = stream.ReadFully();
                }
            }

            var encoding = req.GetCompressionType();
            var cacheKeyEncoded = encoding != null ? cacheInfo.CacheKey + "." + encoding : null;
            if (responseBytes != null || req.ResponseContentType.IsBinary())
            {
                if (responseBytes == null)
                    responseBytes = HostContext.ContentTypes.SerializeToBytes(req, dto);

                cache.Set(cacheInfo.CacheKey, responseBytes, expiresIn);

                if (encoding != null)
                {
                    res.AddHeader(HttpHeaders.ContentEncoding, encoding);
                    responseBytes = responseBytes.CompressBytes(encoding);
                    cache.Set(cacheKeyEncoded, responseBytes, expiresIn);
                }
            }
            else
            {
                var serializedDto = req.SerializeToString(dto);
                if (req.ResponseContentType.MatchesContentType(MimeTypes.Json))
                {
                    var jsonp = req.GetJsonpCallback();
                    if (jsonp != null)
                        serializedDto = jsonp + "(" + serializedDto + ")";
                }

                responseBytes = serializedDto.ToUtf8Bytes();
                cache.Set(cacheInfo.CacheKey, responseBytes, expiresIn);

                if (encoding != null)
                {
                    responseBytes = responseBytes.CompressBytes(encoding);
                    cache.Set(cacheKeyEncoded, responseBytes, expiresIn);
                    res.AddHeader(HttpHeaders.ContentEncoding, encoding);
                }
            }

            var doHttpCaching = cacheInfo.MaxAge != null || cacheInfo.CacheControl != CacheControl.None;
            if (doHttpCaching)
            {
                var cacheControl = BuildCacheControlHeader(cacheInfo);
                if (cacheControl != null)
                {
                    var lastModified = cacheInfo.LastModified.GetValueOrDefault(DateTime.UtcNow);
                    cache.Set("date:" + cacheInfo.CacheKey, lastModified, expiresIn);
                    res.AddHeaderLastModified(lastModified);
                    res.AddHeader(HttpHeaders.CacheControl, cacheControl);

                    if (encoding != null)
                        res.AddHeader(HttpHeaders.Vary, "Accept-Encoding");
                    if (cacheInfo.VaryByUser)
                        res.AddHeader(HttpHeaders.Vary, "Cookie");
                }
            }

            if (httpResult != null)
            {
                foreach (var header in httpResult.Headers)
                {
                    res.AddHeader(header.Key, header.Value);
                }
            }

            res.WriteBytesToResponse(responseBytes, req.ResponseContentType);
            return true;
        }
开发者ID:yuinlin,项目名称:ServiceStack,代码行数:90,代码来源:HttpCacheFeature.cs

示例15: CreateChallenge

        /// <summary>
        /// Create a WWW-Authorize header
        /// </summary>
        public void CreateChallenge(IRequest request, IResponse response)
        {
            var nonce = _nonceService.CreateNonce();

            var challenge = new StringBuilder();
            challenge.AppendFormat(@"Digest realm=""{0}"", ", _realmRepository.GetRealm(request));
            challenge.AppendFormat(@"nonce=""{0}"", ", nonce);
            challenge.Append(@"qop=""auth"", ");
            challenge.Append("algorithm=MD5");


            /* RFC 2617 3.3
                Because the client is required to return the value of the opaque
               directive given to it by the server for the duration of a session,
               the opaque data may be used to transport authentication session state
               information. (Note that any such use can also be accomplished more
               easily and safely by including the state in the nonce.) For example,
               a server could be responsible for authenticating content that
               actually sits on another server. It would achieve this by having the
               first 401 response include a domain directive whose value includes a
               URI on the second server, and an opaque directive whose value            
               contains the state information. The client will retry the request, at
               which time the server might respond with a 301/302 redirection,
               pointing to the URI on the second server. The client will follow the
               redirection, and pass an Authorization header , including the
               <opaque> data.
            */
            // , opaque=""" + Guid.NewGuid().ToString().Replace("-", string.Empty) + "\""


            /* Disable the stale mechanism
             * We should really generate the responses directly in these classes.
            challenge.Append(", stale=");
            challenge.Append((bool)options[0] ? "true" : "false");
            challenge.Append("false");
             * */


            response.AddHeader("WWW-Authorize", challenge.ToString());
        }
开发者ID:samuraitruong,项目名称:comitdownloader,代码行数:43,代码来源:DigestAuthenticator.cs


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