Need to understand short ASP.NET source code - c#

I am maintaining a customer Classic ASP website, and some ASP.NET code was found in a specific place.
I need someone to help me understand the meaning of each line, because I will have to replace this ASP.NET code with Classic ASP functions.
From my understanding, here is what the code performs :
Get the Request.QueryString url, and put it into a variable named str
Redirect (send a HTTP 302) to the Url-Decoded value of str
I would be sure not missing anything else. Is my understanding full and complete ?
Thank you all .NET folks :)
<%# WebHandler Language="C#" Class="GenericHandler1" %>
using System;
using System.Web;
public class GenericHandler1 : IHttpHandler {
public void ProcessRequest (HttpContext context) {
string str = context.Request.QueryString.Get("url");
// context.Response.Redirect( context.Server.UrlDecode(str));
HttpContext.Current.Response.Redirect(context.Server.UrlDecode(str), false);
}
public bool IsReusable {
get
{
return false;
}
}
}

Your understanding is correct. This is a simple HTTP Handler that decodes URLs and redirects the request to the decoded location.
This is not strictly required in many modern sites but it is a hack that can simplify interpreting url parameters if your site does a lot of it from first principals or in scenarios where you believe the original parameters might be double encoded.
To fully replicate the implementation, you probably don't need to replicate this code at all, not in a global sense. Instead look into the web.config or global.asax.cs or if this is more recent look for startup.cs in one of those files should be the registration for this handler, look for any references to GenericHandler1. When you find that code, you will have found the rest of the implementation detail that you may need to consider implementing.
This is a strange thing to ask, "replicate an ASP.Net website in classic ASP". I'm sure you have your business reasons, but have you instead considered upgrading to an OWIN implementation, perhaps with ASP.Net Core? This is usually the easier option if your requirement is to deploy to non IIS host.

Related

Is Request.Cookies["value"] in c# controller some static reference

I am having difficulty to understand some code from GitHub (I am learning angular, however this is server side code written in c#)
The code is available on GitHub code).
I can't completely understand the very first line of code var refreshToken = Request.Cookies["refreshToken"]; Where does Request.Cookies come from? It is not a variable and it looks like a static call to some array Cookies. How does the element of that array happen to contain "refresh-token" item?
Could someone please explain this? (this code comes from the class derived from BaseController)
[HttpPost("refresh-token")]
public ActionResult<AuthenticateResponse> RefreshToken()
{
var refreshToken = Request.Cookies["refreshToken"];
var response = _accountService.RefreshToken(refreshToken, ipAddress());
setTokenCookie(response.RefreshToken);
return Ok(response);
}
When you work in an HTTP application, .NET manages some context for you. A bunch of stuff you write, like your POST action, is provided with an HTTP context, which has properties that provide information about the request. This includes headers, cookies, etc.
When you use Request within an MVC controller (or some other HTTP context) you'll get access to the HttpContext and Request that relates to the specific single request. It feels like magic, but it's the framework doing the work for you.
A bit more information on context.
You need to check other serverside codes which set the cookie,Cookie is created in serverside firstly and sent to User Agent,often stored in your browser.next time you send a request,your request may contain the cookie
you could check the codes like:Response.Cookies.Append(....)

URL Rewriting using ASP.NET 3.5 with C#

I need to rewrite the URL using ASP.NET with code behind as C#. My Application contains the following URL...
http://www.mywebsite.com/Products.aspx?id=1&pg=1
However, I need to rewrite the URL in such a way that the user gets the same contents of the above URL when the user types the following URL...
http://www.mywebsite.com/CategoryName/ProductName/1
Can any of you guys help me with the complete necessary code how to do it?
I mean the web.config, Global.asax, etc...
If you have IIS7, the best option would be to use IIS Url Rewrite Module.
There might be a couple of options I could suggest:
One
You could look at setting up an HttpHandlerFactory.
I have written one myself: http://mvcsnippets.blogspot.co.uk/2012/10/custom-cms-using-httphandlerfactory.html
here is the basic gist:
namespace Web.Helpers {
public class HttpCMSHandlerFactory : IHttpHandlerFactory
{
public IHttpHandler GetHandler(HttpContext context, string requestType, string url,string pathTranslated)
{
string pageName = Path.GetFileNameWithoutExtension(context.Request.PhysicalPath);
//on Server.Transfer the context is kept, so this just overrides the existing value.
if (context.Items.Contains("PageName"))
{
context.Items["PageName"] = pageName; } else { context.Items.Add("PageName", pageName); }
FileInfo fi = new FileInfo(context.Request.MapPath(context.Request.CurrentExecutionFilePath));
//if File is not physical
if (fi.Exists == false)
{
//return page to CMS handler the context containing "PageName" is passed on to this page, which then calls to the database to return the copy.
return PageParser.GetCompiledPageInstance(url, context.Server.MapPath("~/CMSPage.aspx"), context);
}
else
{
// Returns real page.
return PageParser.GetCompiledPageInstance(context.Request.CurrentExecutionFilePath, fi.FullName, context);
}
}
}
The behaviour I was trying to handle was that if there might be CMS content and I didnt want to have to create a page each time I needed information served, but if a physical page exists that should be returned.
For you, you might want to accept the URL, break it down to the component parts.
so http://www.mywebsite.com/CategoryName/ProductName/1 becomes:
context.Items["Categoryname"] = valueFromUrlasCategoryName;
context.Items["Productname"] = valueFromUrlasProductName;
context.Items["Id"] = valueFromUrlasId (or pg);
return PageParser.GetCompiledPageInstance(url, context.Server.MapPath("~/ControlPage.aspx"), context);
Then on your control page you can intercept these values from the context passed in and interrogate the data as needed.
In the web.config you point a reference towards your HttpHandlerFactory
<httphandlers>
<add path="*.aspx" type="Web.Helpers.HttpCMSHandlerFactory, Web.helpers" verb="*"/>
</httphandlers>
In your case you could set the path as "." to capture all traffic. this would mean you would have to add handling for images and scripts.
you will also need to make sure you add a wildcard to your IIS for extensionless pages.
There are plenty of articles about HttpHandlerFactories on the web, and might explain better.
Two
The sort of thing you are after is part of MVC, could you look at changing your UI to use that?

Redirecting webpage in ASP.NET depending on the URL

I've a domain name called mywebsite.com but I prefer users to access to my website through the www subdomain.
How can I achieve a verification and redirection in asp.net mvc3 easily?
When I was using php I did something like that :
if($_SERVER['SERVER_NAME'] != "www.mywebsite.com")
header('Location: www.mywebsite.com');
I'd like to find a similar way to achieve this kind of redirection in asp.net (C#) (I'd prefer not to set a 301 redirection but just a soft redirection like the one I was using in PHP).
I know I could do a verification in each of my controllers action methods and the redirect the user if he is not on the subdomain www.mywebsite.com but I'd prefer to write once the verification and the redirection and I can't find where :/
Thanks a lot !
You could use:
Request.Url.ToString()
This will return the URL , then you can quickly check if it contains 'www.' and redirect if true. However I would suggest that your handle this in the URL rewrite in IIS.
Follow the guide here: http://www.dotnetexpertguide.com/2011/08/iis-7-redirect-domaincom-to.html this is for making domain.com go to www.domain.com, but it works the same way for the opposite.
you could try something like this
if(!Request.Url.Host.Equals("www.mywebsite.com"))
{
Response.Redirect("website");
}
If you are looking to just add/append header information, then use Response.AppendHeader().
The Request.Url.ToString() property can be checked for the url you are looking for as per Ryan's answer.
Actually, the original question asks specifically for a 'soft' redirection (201 or 202) instead of a Moved Permanently/Found (301/302), so i think that instead of Response.Redirect the conditional line should be:
if(!Request.Url.Host.Equals("www.mywebsite.com"))
{
HttpContext.Current.Response.Headers.Add("Location", "www.mywebsite.com");
}
EDIT: I believe the status may also be set directly, used in conjunction with Response.Redirect:
if(!Request.Url.Host.Equals("www.mywebsite.com"))
{
HttpContext.Current.Response.Redirect("www.mywebsite.com");
HttpContext.Current.Response.Status = "201 Created";
}
If I am not totally missing something here, can't you just setup the host-header in the IIS settings for the site to include both www.domain.com as well as domain.com?

Passing parameters from silverlight to ASP.net

I've made a little game in silverlight that records users scores whilst they play.
I decided it would be a lot better if I could implement a leaderboard, so I created a database in mySQL to store all the high scores along with names and dates. I have created some communications to the database in ASP.net. This works and I can simply insert and get data within the code.
It's now time to link the silverlight project with the ASP.net database communications, so I can send the users name and score as variables to my ASP.net code and then it will upload it to the database. That's all I need. Surely there must be an easy way of doing this, I just can't seem to find any ways when researching.
Thanks in advance,
Lloyd
At first you need add Generic Handler to your ASP.Net project.
public class Handler1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string userName = context.Request["user"];
int score = int.Parse(context.Request["score"]);
//And store it in DB
}
}
After you need call this handler from SilverLight app:
string uri = HtmlPage.Document.DocumentUri.ToString();
// Remove the web page from the current URI to get the root URI.
string rootUri = uri.Remove(uri.LastIndexOf('/'),
uri.Length - uri.LastIndexOf('/'));
string diggUrl = String.Format(rootUri + "/" + "test.ashx?user={0}&score={1}", "testuser", "234");
// Initiate Async Network call to Digg
WebClient diggService = new WebClient();
diggService.DownloadStringAsync(new Uri(diggUrl));
here i used Uri Class to send parameter to asp.net, but you can send string format only.
// this code written on Silverlight Button Click Event.
Uri myURI = new Uri(HtmlPage.Document.DocumentUri,String.Format("Report.aspx?brcd={0}&acc={1}&user={2}", Brcd, Acc, User)); HtmlPage.Window.Navigate(myURI, "_blank");
below code is written on Asp.net page_load or page init event
Brcd = Request.QueryString["brcd"];// brcd value accept here.
acc= Request.QueryString["ACC"];`
user= Request.QueryString["User"];
in above code we accept the silverlight parameter in asp.net but in [] bracket put name as it is use in silverlight page because it case sensitive.
By ASP.NET, do you mean an ASP.NET Webforms app?
If so, an ASP.NET Webforms app is a method of building a UI. What you need is an API, for your Silverlight app to use programatically. For this purpose you may want to consider building an ASP.NET Webservice instead, which provides an API over HTTP.
What do you need its to send data to web server from a Silverlight application, right?
You can:
Call Javascript functions from Silverlight and, there, do a postback
Call web services with Silverlight, but make sure its in same server which your SL application came from, or you will face some XSS issues.
An easy way to do this is to have your Silverlight code create a REST URL by encoding the information into the query string, and invoking an .aspx page on the server. The page wouldn't need to return any markup; it would just handle the back-end stuff and return.
Alternatively, you could make a web service call from Silverlight to your back end.
I prefer the latter approach. It's a little more work the first time through, but it's also more general purpose and makes for generally better code in the long run.
Although technically you could use JavaScript, I wouldn't suggest it; why go backwards in tech if you don't have to?

.Net Form POST

I've got a client that, during testing, is giving me conflicting information. I don't think they are lying but more confused. So, I would like to setup some simple auditing in my ASP.Net application. Specifically, right when any page is called, I want to immediately insert the Querystring and/or form POST data into a log table. Just the raw values.
Querystring is easy. But there doesn't seem to be a way to get the raw form POST'ed data without using BinaryRead, and if I do that, then I screw myself out of using the Request.Form collection later on.
Does anyone know a way around this?
EDIT: tvanfosson suggested Request.Params. I was looking for something that was easier to use (like Request.Querystring, only for POST), but I guess I could just as easily loop through all params and build a string of name=value&, etc).
You can create a custom HttpModule to capture all request made to your application so you don't need to touch every page and you can use it only during testing just not to slow down performance in production.
A sample implementation would be:
public class CustomModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.EndRequest += new EventHandler(context_BeginRequest);
}
private void context_BeginRequest(object sender, EventArgs e)
{
HttpContext context = ((HttpApplication)sender).Context;
// you can use the context.Request here to send it to the database or a log file
}
}
You need to add the module to your web.config
<httpModules>
<add name="CustomModule" type="CustomModule"/>
</httpModules>
All of the form data should be in Request.Params. You'd need to do this on every page, though or maybe use an HttpModule.
[EDIT] If you want to get the form parameters separately use Request.Form, along with Request.QueryString
I would recommend implementing and HttpHandler or an HttpModule for this type of scenario. You can get to the POST Data from the Page_Load event but implementing this logging facility here is not as maintainable.

Categories

Resources