本文整理汇总了C#中HttpResponse类的典型用法代码示例。如果您正苦于以下问题:C# HttpResponse类的具体用法?C# HttpResponse怎么用?C# HttpResponse使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
HttpResponse类属于命名空间,在下文中一共展示了HttpResponse类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Login
public HttpResponse Login()
{
var userRepo = UserRepositoryLocator.Instance;
HttpResponse response = null;
var authentication = Context.Request.Headers["Authorization"];
//se não existir header, realizar basic authentication
if(authentication == null)
{
response = new HttpResponse(HttpStatusCode.Unauthorized, new TextContent("Not Authorized"))
.WithHeader("WWW-Authenticate", "Basic realm=\"Private Area\"");
}else
{
authentication = authentication.Replace("Basic ", "");
string userPassDecoded = Encoding.UTF8.GetString(Convert.FromBase64String(authentication));
string[] userPasswd = userPassDecoded.Split(':');
string username = userPasswd[0];
string passwd = userPasswd[1];
User user = null;
if (userRepo.TryAuthenticate(username, passwd, out user))
{
response = new HttpResponse(HttpStatusCode.Found).WithHeader("Location", "/")
.WithCookie(new Cookie(COOKIE_AUTH_NAME, user.Identity.Name, "/"));
}
}
return response;
}
示例2: GenerateImage
private void GenerateImage(
HttpResponse response,
string textToInsert,
int width,
int height,
Color backgroundColor,
FontFamily fontFamily,
float emSize,
Brush brush,
float x,
float y,
string contentType,
ImageFormat imageFormat)
{
using (Bitmap bitmap = new Bitmap(width, height))
{
using (Graphics graphics = Graphics.FromImage(bitmap))
{
graphics.Clear(backgroundColor);
graphics.DrawString(textToInsert, new Font(fontFamily, emSize), brush, x, y);
response.ContentType = contentType;
bitmap.Save(response.OutputStream, imageFormat);
}
}
}
示例3: FromString
public static HttpResponse FromString(string value)
{
var result = new HttpResponse();
result.Line = HttpStatusLine.FromString(result.Load(value));
return result;
}
示例4: Uninitialize
public virtual void Uninitialize()
{
_features = default(FeatureReferences<FeatureInterfaces>);
if (_request != null)
{
UninitializeHttpRequest(_request);
_request = null;
}
if (_response != null)
{
UninitializeHttpResponse(_response);
_response = null;
}
if (_authenticationManager != null)
{
UninitializeAuthenticationManager(_authenticationManager);
_authenticationManager = null;
}
if (_connection != null)
{
UninitializeConnectionInfo(_connection);
_connection = null;
}
if (_websockets != null)
{
UninitializeWebSocketManager(_websockets);
_websockets = null;
}
}
示例5: CompetitionResultAppelRequestHandler
public CompetitionResultAppelRequestHandler(HttpRequest Request, HttpResponse Response, Uri Prefix, UriTemplate CompetitionResultsTemplate, UriTemplate ResultResourceTemplate, string AcceptHeader)
: base(Request, Response, Prefix, AcceptHeader)
{
this.CompetitionResultsTemplate = CompetitionResultsTemplate;
this.ResultResourceTemplate = ResultResourceTemplate;
processRequest();
}
示例6: login
public void login(HttpRequest request, HttpResponse response, System.Web.SessionState.HttpSessionState session)
{
if(String.IsNullOrEmpty(serviceLogoutUrl))
throw new Exception("ERROR: service Logout Url not defined");
if(String.IsNullOrEmpty(centralizedSPUrl))
throw new Exception("ERROR: centralized SP Url not defined");
if(String.IsNullOrEmpty(request.Params["xmlAttrib"])){
string serviceUrl = request.RawUrl;
string auth = "<auth><serviceURL>"+serviceUrl+"</serviceURL><logoutURL>"+serviceLogoutUrl+"</logoutURL>";
if(!String.IsNullOrEmpty(authenticationMethodList)){
auth += "<authnContextList>";
foreach(string authenticationMethod in authenticationMethodList)
auth += "<authnContext>"+authenticationMethod+"</authnContext>";
auth += "</authnContextList>";
}
auth += "</auth>";
string authB64 = Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(auth));
response.Redirect(centralizedSPUrl+"/PoA?xmlAuth="+System.Web.HttpUtility.UrlEncode(authB64));
} else {
string userAttributes = System.Text.Encoding.ASCII.GetString(Convert.FromBase64String(request.Params["xmlAttrib"]));
session["userAttributes"] = userAttributes;
if(!String.IsNullOrEmpty(request.Params["ReturnUrl"]))
response.Redirect(request.Params["ReturnUrl"]);
}
}
示例7: ResponseFile
public bool ResponseFile(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullUrl, long _speed)
{
try
{
FileStream myFile = new FileStream(_fullUrl, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
BinaryReader br = new BinaryReader(myFile);
try
{
_Response.AddHeader("Accept-Ranges", "bytes");
_Response.Buffer = false;
long fileLength = myFile.Length;
long startBytes = 0;
int pack = 10240; //10K bytes
int sleep = (int)Math.Floor((double)(1000 * pack / _speed)) + 1;
if (_Request.Headers["Range"] != null)
{
_Response.StatusCode = 206;
string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' });
startBytes = Convert.ToInt64(range[1]);
}
_Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
if (startBytes != 0)
{
_Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength));
}
_Response.AddHeader("Connection", "Keep-Alive");
_Response.ContentType = "application/octet-stream";
_Response.AddHeader("Content-Disposition", "attachment;filename="
+ HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8));
br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
int maxCount = (int)Math.Floor((double)((fileLength - startBytes) / pack)) + 1;
for (int i = 0; i < maxCount; i++)
{
if (_Response.IsClientConnected)
{
_Response.BinaryWrite(br.ReadBytes(pack));
Thread.Sleep(sleep);
}
else
{
i = maxCount;
}
}
}
catch
{
return false;
}
finally
{
br.Close();
myFile.Close();
}
}
catch
{
return false;
}
return true;
}
示例8: SetLanguage
public static void SetLanguage(string Language, HttpResponse Response)
{
HttpCookie cookie = new HttpCookie("DareLang");
cookie.Value = Language;
cookie.Expires = DateTime.Now.AddYears(7);
Response.Cookies.Add(cookie);
}
示例9: ExchangeHTTP
public ExchangeHTTP(HttpResponse response, string flag)
{
this.encoding = response.Output.Encoding;
this.responseStream = response.Filter;
this.flag = flag;
}
示例10: SignOut
public static void SignOut(HttpResponse Response, HttpRequest Request)
{
HttpCookie cookie = Request.Cookies["DareSessionID"];
int id = int.Parse(cookie.Value);
SessionManager.RemoveSession(id);
if (Response.Cookies.AllKeys.Contains("DareSessionID")) Response.Cookies.Remove("DareSessionID");
}
示例11: ToHttpCall
public static HttpResponse ToHttpCall(this WebRequest request)
{
var reset = new ManualResetEvent(false);
IAsyncResult result = null;
var thread = new Thread(() =>
{
result = request.BeginGetResponse(r => { }, null);
reset.Set();
});
thread.Start();
thread.Join();
reset.WaitOne();
try
{
var response = request.EndGetResponse(result).As<HttpWebResponse>();
return new HttpResponse(response);
}
catch (WebException e)
{
if (e.Response == null)
{
throw;
}
var errorResponse = new HttpResponse(e.Response.As<HttpWebResponse>());
return errorResponse;
}
}
示例12: WriteResponseForPostJson
void WriteResponseForPostJson(HttpRequest request, HttpResponse response)
{
// read request JSON
uint requestedCount = ReadCount(request.Body);
// write response JSON
var json = new JsonWriter<ResponseFormatter>(response.Body, prettyPrint: false);
json.WriteObjectStart();
json.WriteArrayStart();
for (int i = 0; i < requestedCount; i++) {
json.WriteString("hello!");
}
json.WriteArrayEnd();
json.WriteObjectEnd();
// write headers
var headers = response.Headers;
headers.AppendHttpStatusLine(HttpVersion.V1_1, 200, new Utf8String("OK"));
headers.Append("Content-Length : ");
headers.Append(response.Body.CommitedBytes);
headers.AppendHttpNewLine();
headers.Append("Content-Type : text/plain; charset=UTF-8");
headers.AppendHttpNewLine();
headers.Append("Server : .NET Core Sample Server");
headers.AppendHttpNewLine();
headers.Append("Date : ");
headers.Append(DateTime.UtcNow, 'R');
headers.AppendHttpNewLine();
headers.AppendHttpNewLine();
}
示例13: pageHome
public static void pageHome(ref UberCMS.Misc.PageElements pageElements, HttpRequest request, HttpResponse response, ref StringBuilder content)
{
content.Append(
templates[TEMPLATES_KEY]["home"]
);
pageElements["TITLE"] = "Welcome!";
}
示例14: 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);
}
示例15: Handle
public void Handle(HttpRequest req, HttpResponse resp, JsonRpcHandler jsonRpcHandler)
{
if(req.HttpMethod != "POST")
{
resp.Status = "405 Method Not Allowed";
return;
}
if(!req.ContentType.StartsWith("application/json"))
{
resp.Status = "415 Unsupported Media Type";
return;
}
JToken json;
try
{
json = JToken.ReadFrom(new JsonTextReader(req.Content));
}
catch(Exception e)
{
resp.Status = "400 Bad Request";
resp.ContentType = "text/plain";
resp.Content.WriteLine(e);
return;
}
resp.Status = "200 OK";
resp.ContentType = "application/json";
using(var jsonWriter = new JsonTextWriter(resp.Content))
{
new JsonSerializer().Serialize(jsonWriter, jsonRpcHandler.Handle(json));
}
}