本文整理汇总了C#中HttpContext类的典型用法代码示例。如果您正苦于以下问题:C# HttpContext类的具体用法?C# HttpContext怎么用?C# HttpContext使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
HttpContext类属于命名空间,在下文中一共展示了HttpContext类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。
示例1: Add
void Add(HttpContext context)
{
context.Response.ContentType = "application/json";
string name = context.Request["text"];
string msg = string.Empty;
if (!string.IsNullOrWhiteSpace(name)) {
try {
Guid id= System.Guid.NewGuid() ;
IList<Module> modules = RepositoryFactory<Modules>.Get().GetAll();
var query = from p in modules
select new Right { ModuleId = p.Id , Permission = 0 , RoleId = id };
Role obj = new Role { Id =id, Name = context.Server.UrlDecode(name),Rights=query.ToList() };
RepositoryFactory<RolesRepository>.Get().Add(obj);
context.Response.Write("{\"id\":\"" + obj.Id.ToString() + "\"}");
AppLog.Write("创建角色", AppLog.LogMessageType.Info,"name="+obj.Name,this.GetType());
} catch (Exception ex) {
AppLog.Write("创建角色 出错" , AppLog.LogMessageType.Error , "name=" + name , ex , this.GetType());
msg = ex.Message;
}
} else {
msg = "角色名不能为空";
}
if (!string.IsNullOrWhiteSpace(msg)) {
context.Response.Write("{\"msg\":\""+msg+"\"}");
}
}
开发者ID:HuGuo,项目名称:TSS,代码行数:30,代码来源:RoleHandler.cs
示例2: Evaluate
override object Evaluate (HttpContext ctx, Control control)
{
if (control == null)
return null;
if (control.Page == null)
return null;
if(String.IsNullOrEmpty(ControlID))
throw new ArgumentException ("The ControlID property is not set.");
Control c = null, namingContainer = control.NamingContainer;
while (namingContainer != null) {
c = namingContainer.FindControl(ControlID);
if (c != null)
break;
namingContainer = namingContainer.NamingContainer;
}
if (c == null)
throw new InvalidOperationException ("Control '" + ControlID + "' not found.");
string propName = PropertyName;
if (String.IsNullOrEmpty (propName)) {
object [] attrs = c.GetType ().GetCustomAttributes (typeof (ControlValuePropertyAttribute), true);
if(attrs.Length==0)
throw new ArgumentException ("The PropertyName property is not set and the Control identified by the ControlID property is not decorated with a ControlValuePropertyAttribute attribute.");
ControlValuePropertyAttribute attr = (ControlValuePropertyAttribute) attrs [0];
propName = attr.Name;
}
return DataBinder.Eval (c, propName);
}
开发者ID:nobled,项目名称:mono,代码行数:32,代码来源:ControlParameter.cs
示例3: Invoke
public Task Invoke(HttpContext context)
{
var path = context.Request.Path.Value.TrimStart('/');
var response = context.Response;
if (path == "topics.js")
{
response.Headers["content-type"] = "text/javascript";
return response.WriteAsync(_topicJS);
}
var topic = _project.FindTopicByUrl(path);
if (topic == null)
{
response.StatusCode = 404;
response.Headers["content-type"] = "text/plain";
return response.WriteAsync("Unknown topic");
}
response.Headers["cache-control"] = "no-cache, no-store, must-revalidate";
response.Headers["pragma"] = "no-cache";
response.Headers["expires"] = "0";
var html = GenerateHtml(topic);
response.Headers["content-type"] = "text/html";
return response.WriteAsync(html);
}
开发者ID:storyteller,项目名称:Storyteller,代码行数:30,代码来源:TopicMiddleware.cs
示例4: RetrieveFileData
private void RetrieveFileData(HttpContext context, string filePath, string container)
{
MediaFileModel resultModel = new MediaFileModel();
// only send request to imageprocessor if querystring exists; can exclude other parameters if needed
if (context.Request.RawUrl.Contains("?"))
{
resultModel = MediaHelper.GetMediaFile(filePath, container, context.Request.RawUrl);
}
else
{
resultModel = MediaHelper.GetMediaFile(filePath, container);
}
if (resultModel.RedirectToAzureStorage)
{
context.Response.Redirect(filePath.Replace($"/{container}", $"{ConfigurationManager.AppSettings["BlobStorage"]}/{container}"), true);
}
var myTimeSpan = new TimeSpan(7, 0, 0, 0);
context.Response.Cache.SetCacheability(HttpCacheability.Public);
context.Response.Cache.SetValidUntilExpires(true);
context.Response.Cache.SetMaxAge(myTimeSpan);
context.Response.Cache.SetLastModified(resultModel.LastModifiedDate);
context.Response.Cache.SetETag(resultModel.ETag.Replace("\\\"", ""));
context.Response.AddHeader("Content-MD5", resultModel.ContentMd5);
context.Response.ContentType = resultModel.ContentType;
// replicate properties returned by blob storage
context.Response.AddHeader("Server", "Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0");
context.Response.AddHeader("x-ms-request-id", Guid.NewGuid().ToString());
context.Response.AddHeader("x-ms-version", "2009-09-19");
context.Response.AddHeader("x-ms-lease-status", "unlocked");
context.Response.AddHeader("x-ms-blob-type", "BlockBlob");
context.Response.OutputStream.Write(resultModel.ImageData, 0, resultModel.ImageData.Length);
context.Response.AddHeader("Content-Length", resultModel.ImageData.Length.ToString());
context.Response.Flush();
context.Response.End();
}
开发者ID:tstahnke,项目名称:umbraco-azure-cdn,代码行数:35,代码来源:MediaModule.cs
示例5: Invoke
/// <summary>
/// This examines the request to see if it matches a configured directory, and if there are any files with the
/// configured default names in that directory. If so this will append the corresponding file name to the request
/// path for a later middleware to handle.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public Task Invoke(HttpContext context)
{
IEnumerable<IFileInfo> dirContents;
PathString subpath;
if (Helpers.IsGetOrHeadMethod(context.Request.Method)
&& Helpers.TryMatchPath(context, _matchUrl, forDirectory: true, subpath: out subpath)
&& _options.FileSystem.TryGetDirectoryContents(subpath.Value, out dirContents))
{
// Check if any of our default files exist.
for (int matchIndex = 0; matchIndex < _options.DefaultFileNames.Count; matchIndex++)
{
string defaultFile = _options.DefaultFileNames[matchIndex];
IFileInfo file;
// TryMatchPath will make sure subpath always ends with a "/" by adding it if needed.
if (_options.FileSystem.TryGetFileInfo(subpath + defaultFile, out file))
{
// If the path matches a directory but does not end in a slash, redirect to add the slash.
// This prevents relative links from breaking.
if (!Helpers.PathEndsInSlash(context.Request.Path))
{
context.Response.StatusCode = 301;
context.Response.Headers[Constants.Location] = context.Request.PathBase + context.Request.Path + "/";
return Constants.CompletedTask;
}
// Match found, re-write the url. A later middleware will actually serve the file.
context.Request.Path = new PathString(context.Request.Path.Value + defaultFile);
break;
}
}
}
return _next(context);
}
开发者ID:WillSullivan,项目名称:StaticFiles,代码行数:41,代码来源:DefaultFilesMiddleware.cs
示例6: Invoke
public Task Invoke(HttpContext httpContext)
{
var clientManager = httpContext.RequestServices.GetService<ClientManager>();
clientManager.Init(httpContext);
return _next(httpContext);
}
开发者ID:284247028,项目名称:DotNetClub,代码行数:7,代码来源:ClientManagerInitializerMiddleware.cs
示例7: ProcessRequest
public void ProcessRequest(HttpContext context)
{
System.Drawing.Image Cover;
//判断请求的物理路径中,是否存在文件
if (File.Exists(context.Request.PhysicalPath))
{
//加载文件
Cover = Image.FromFile(context.Request.PhysicalPath);
//加载水印图片
Image watermark = Image.FromFile(context.Request.MapPath(WATERMARK_URL));
//实例化画布
Graphics g = Graphics.FromImage(Cover);
//在image上绘制水印
g.DrawImage(watermark, new Rectangle(Cover.Width - watermark.Width, Cover.Height - watermark.Height, watermark.Width, watermark.Height), 0, 0, watermark.Width, watermark.Height, GraphicsUnit.Pixel);
//释放画布
g.Dispose();
//释放水印图片
watermark.Dispose();
}
else
{
//加载默认图片
Cover = Image.FromFile(context.Request.MapPath(DEFAULTIMAGE_URL));
}
//设置输出格式
context.Response.ContentType = "image/jpeg";
//将图片存入输出流
Cover.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
Cover.Dispose();
context.Response.End();
}
开发者ID:muupu,项目名称:BookShop,代码行数:31,代码来源:CoverHandler.cs
示例8: ProcessRequest
async Task ProcessRequest(HttpContext context)
{
try
{
context.Response.ContentType = "application/json; charset=utf-8";
context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
string code = context.Request.Query["code"];
if (code == null)
{
#if !DEBUG
context.Response.Redirect("https://silentorbit.com/lax/");
#endif
await context.Response.WriteAsync("{\"error\": \"no code\"}");
return;
}
var response = WebCompiler.Compile(code);
string json = JsonConvert.SerializeObject(response, Formatting.Indented);
await context.Response.WriteAsync(json);
}
catch (Exception ex)
{
await context.Response.WriteAsync(ex.Message);
}
}
开发者ID:hultqvist,项目名称:lax,代码行数:25,代码来源:Startup.cs
示例9: AppendCookieContext
public AppendCookieContext(HttpContext context, CookieOptions options, string name, string value)
{
Context = context;
CookieOptions = options;
CookieName = name;
CookieValue = value;
}
开发者ID:CoryGM,项目名称:Security,代码行数:7,代码来源:AppendCookieContext.cs
示例10: ProcessRequest
public void ProcessRequest(HttpContext context)
{
MoSmsResp moSmsResp = null;
string jsonString="";
context.Response.ContentType = "application/json";
try
{
byte[] PostData = context.Request.BinaryRead(context.Request.ContentLength);
jsonString = Encoding.UTF8.GetString(PostData);
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
MoSmsReq moSmsReq = json_serializer.Deserialize<MoSmsReq>(jsonString);
moSmsResp = GenerateStatus(true);
onMessage(moSmsReq);
}
catch (Exception)
{
moSmsResp = GenerateStatus(false);
}
finally
{
if (jsonString.Equals(""))
context.Response.Write(APPLICATION_RUNING_MESSAGE);
else
context.Response.Write(moSmsResp.ToString());
}
}
开发者ID:SajithLakjaya,项目名称:Ideamart-C-Sharp-SMS-SDK,代码行数:26,代码来源:SmsListener.cs
示例11: BasicAuthInfo
/// <summary>
/// Main constructor to create <see cref="BasicAuthInfo"/>
/// </summary>
/// <param name="credential">Basic auth credential from the request</param>
/// <param name="properties">Basic auth properties from the request</param>
/// <param name="httpContext">Context from the request</param>
/// <param name="authenticationScheme">Authentication scheme from the configuration</param>
internal BasicAuthInfo(BasicAuthCredential credential, AuthenticationProperties properties, HttpContext httpContext, string authenticationScheme)
{
this.Credential = credential;
this.Properties = properties;
this.HttpContext = httpContext;
this.AuthenticationScheme = authenticationScheme;
}
开发者ID:edjCase,项目名称:BasicAuth,代码行数:14,代码来源:BasicAuthInfo.cs
示例12: Invoke
public async Task Invoke(HttpContext httpContext)
{
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("Begin Routing Request");
}
var shellSettings = (ShellSettings)httpContext.Features[typeof(ShellSettings)];
RequestDelegate pipeline;
if (!_pipelines.TryGetValue(shellSettings.Name, out pipeline))
{
// Building a pipeline can't be done by two requests
lock (_pipelines)
{
if (!_pipelines.TryGetValue(shellSettings.Name, out pipeline))
{
pipeline = BuildTenantPipeline(shellSettings, httpContext.RequestServices);
if (shellSettings.State == Environment.Shell.Models.TenantState.Running)
{
// TODO: Invalidate the pipeline automatically when the shell context is changed
// such that we can reload the middlewares and the routes. Implement something similar
// to IRunningShellTable but for the pipelines.
_pipelines.Add(shellSettings.Name, pipeline);
}
}
}
}
await pipeline.Invoke(httpContext);
}
开发者ID:vairam-svs,项目名称:Orchard2,代码行数:34,代码来源:OrchardRouterMiddleware.cs
示例13: ProcessRequest
public void ProcessRequest(HttpContext context)
{
if (!WebUser.IsAuthenticated)
{
throw new HttpException(401, "You must login to do this.");
}
if (!WebUser.HasRole(UserRoles.Admin))
{
throw new HttpException(401, "You do not have permission to do this.");
}
var mode = context.Request.Form["mode"];
var name = context.Request.Form["roleName"];
var id = context.Request.Form["roleId"];
if (mode == "edit")
{
Edit(Convert.ToInt32(id), name);
}
else if (mode == "new")
{
Create(name);
}
else if (mode == "delete")
{
Delete(name);
}
context.Response.Redirect("~/admin/role/");
}
开发者ID:jwmcpeak,项目名称:webpagescms,代码行数:31,代码来源:RoleHandler.cs
示例14: HandleAuthentication
public static bool HandleAuthentication(HttpContext context)
{
string authType = context.Request.QueryString["auth"];
string user = context.Request.QueryString["user"];
string password = context.Request.QueryString["password"];
string domain = context.Request.QueryString["domain"];
if (string.Equals("basic", authType, StringComparison.OrdinalIgnoreCase))
{
if (!HandleBasicAuthentication(context, user, password, domain))
{
context.Response.End();
return false;
}
}
else if (string.Equals("Negotiate", authType, StringComparison.OrdinalIgnoreCase) ||
string.Equals("NTLM", authType, StringComparison.OrdinalIgnoreCase))
{
if (!HandleChallengeResponseAuthentication(context, authType, user, password, domain))
{
context.Response.End();
return false;
}
}
else if (authType != null)
{
context.Response.StatusCode = 501;
context.Response.StatusDescription = "Unsupported auth type: " + authType;
context.Response.End();
return false;
}
return true;
}
开发者ID:ESgarbi,项目名称:corefx,代码行数:34,代码来源:AuthenticationHelper.cs
示例15: Invoke
public async Task Invoke(HttpContext httpContext, RequestTelemetry telemetry)
{
telemetry.Timestamp = DateTimeOffset.UtcNow;
var sw = new Stopwatch();
sw.Start();
bool requestFailed = false;
try
{
await this.next.Invoke(httpContext);
}
catch (Exception)
{
requestFailed = true;
throw;
}
finally
{
sw.Stop();
telemetry.Duration = sw.Elapsed;
telemetry.ResponseCode = httpContext.Response.StatusCode.ToString();
telemetry.Success = (!requestFailed) && (httpContext.Response.StatusCode < 400);
telemetry.HttpMethod = httpContext.Request.Method;
telemetry.Url = httpContext.Request.GetUri();
telemetry.Context.GetInternalContext().SdkVersion = this.sdkVersion;
this.telemetryClient.TrackRequest(telemetry);
}
}
开发者ID:RehanSaeed,项目名称:ApplicationInsights-aspnetcore,代码行数:32,代码来源:RequestTrackingMiddleware.cs
示例16: Invoke
public async Task Invoke(HttpContext context)
{
var responseBody = context.Response.Body;
var requestBody = context.Request.Body;
if (_logger.IsEnabled(LogLevel.Debug))
{
// TODO: Add the feature interface to disable this memory stream
// when we add signalr
context.Response.Body = new MemoryStream();
context.Request.Body = new MemoryStream();
await requestBody.CopyToAsync(context.Request.Body);
LogRequest(context);
}
var stopwatch = Stopwatch.StartNew();
await _next(context);
stopwatch.Stop();
if (_logger.IsEnabled(LogLevel.Debug))
{
LogResponse(context);
await context.Response.Body.CopyToAsync(responseBody);
}
_logger.LogInformation(context.Request.Path + ": " + context.Response.StatusCode + " " + stopwatch.ElapsedMilliseconds + "ms");
}
开发者ID:RLittlesII,项目名称:omnisharp-roslyn,代码行数:31,代码来源:LoggingMiddleware.cs
示例17: OnLogin
async Task OnLogin(HttpContext ctx)
{
LoginWasCalled = true;
await ReadSignInMessage(ctx);
await IssueLoginCookie(ctx);
await CreateSignInResponse(ctx);
}
开发者ID:RajMondaz,项目名称:IdentityServer4,代码行数:7,代码来源:MockAuthorizationPipeline.cs
示例18: Save
private static void Save(HttpContext context, Post post)
{
string name = context.Request.Form["name"];
string email = context.Request.Form["email"];
string website = context.Request.Form["website"];
string content = context.Request.Form["content"];
Validate(name, email, content);
Comment comment = new Comment()
{
Author = name.Trim(),
Email = email.Trim(),
Website = GetUrl(website),
Ip = context.Request.UserHostAddress,
UserAgent = context.Request.UserAgent,
IsAdmin = context.User.Identity.IsAuthenticated,
Content = HttpUtility.HtmlEncode(content.Trim()).Replace("\n", "<br />"),
};
post.Comments.Add(comment);
post.Save();
string wrapper = VirtualPathUtility.ToAbsolute("~/views/commentwrapper.cshtml") + "?postid=" + post.ID + "&commentid=" + comment.ID;
context.Response.Write(wrapper);
}
开发者ID:jf26028,项目名称:MiniBlog,代码行数:26,代码来源:CommentHandler.cs
示例19: Invoke
// 1. Find tenant by hostname.
// 2. If context not created - create it.
public async Task Invoke(HttpContext context)
{
var tenant = _tenantSelector.SelectTenant(context);
if (tenant != null)
{
_logger.LogInformation($"Found appropriate tenant: {tenant.TenantId}");
var tenantContext = _host.LoadContext(tenant);
var tenantServiceProvider = tenantContext.Services;
var pipeline = tenantContext.States.Get<RequestDelegate>();
if (pipeline == null)
{
_logger.LogInformation($"Creating pipeline for tenant: {tenant.TenantId}");
var pipelineFactory = tenantServiceProvider.GetRequiredService<ITenantPipelineFactory>();
pipeline = pipelineFactory.CreatePipeline();
tenantContext.States.Set(pipeline);
var eventBus = tenantServiceProvider.GetRequiredService<IEventBus>();
await eventBus.NotifyAsync<ITenantEvents>(e => e.ActivatedAsync());
}
using (var scope = tenantServiceProvider.CreateScope())
{
context.RequestServices = scope.ServiceProvider;
context.Features.Set(tenantContext);
await pipeline(context);
}
}
else
{
_logger.LogWarning("Appropriate tenant not found, continue executing pipeline.");
await _next(context);
}
}
开发者ID:causer,项目名称:Itasu,代码行数:36,代码来源:HostMiddleware.cs
示例20: HandleWebSocketsAsync
private static async Task HandleWebSocketsAsync(HttpContext context, Func<Task> next)
{
if (!context.WebSockets.IsWebSocketRequest)
{
await next();
return;
}
var hub = context.RequestServices.GetRequiredService<MessageHub>();
using (var webSocket = await context.WebSockets.AcceptWebSocketAsync())
{
try
{
await hub.SubscribeAsync(webSocket);
var buffer = new ArraySegment<byte>(new byte[4096]);
while (webSocket?.State == WebSocketState.Open)
{
await webSocket.ReceiveAsync(buffer, CancellationToken.None);
}
}
finally
{
await hub.UnsubscribeAsync(webSocket);
}
}
}
开发者ID:tuespetre,项目名称:Sleeper,代码行数:29,代码来源:Startup.cs
注:本文中的HttpContext类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论