本文整理汇总了C#中HttpContext类的典型用法代码示例。如果您正苦于以下问题:C# HttpContext类的具体用法?C# HttpContext怎么用?C# HttpContext使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
HttpContext类属于命名空间,在下文中一共展示了HttpContext类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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+"\"}");
}
}
示例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);
}
示例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);
}
示例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();
}
示例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);
}
示例6: Invoke
public Task Invoke(HttpContext httpContext)
{
var clientManager = httpContext.RequestServices.GetService<ClientManager>();
clientManager.Init(httpContext);
return _next(httpContext);
}
示例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();
}
示例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);
}
}
示例9: AppendCookieContext
public AppendCookieContext(HttpContext context, CookieOptions options, string name, string value)
{
Context = context;
CookieOptions = options;
CookieName = name;
CookieValue = value;
}
示例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());
}
}
示例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;
}
示例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);
}
示例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/");
}
示例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;
}
示例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);
}
}