how i can create a page that works like stackoverflow - asp.net

i want to know how did these pages work!
like this :
https://stackoverflow.com/questions/ask
there is no extension in end of the address!
is this a way to call webmethods directly?!
i wrote this page , but i think its not right!
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string name= Request.QueryString["name"];
if (Request.PathInfo == "/SayHi")Response.Write( SayHi(name));
}
[WebMethod]
public static string SayHi(string name)
{
return "Hi " + name;
}
//[WebMethod]
//public static string SayHi()
//{
// return "Hi ";
//}
}

For ASP.NET, you can use ASP.NET Routing, which will allow you to separately configure what the URLs should look like.
You can use it both for regular WebForms apps and with the newer ASP.NET MVC.

Take a look at ASP.Net MVC. It's the framework that runs the Stack Overflow site per this other question. MVC uses the routing engine to allow urls without a trailing ".aspx".

StackOverflow uses ASP.NET MVC as its core web technology and you are right there are no extensions, because there is a routing engine that handles requests.
In your example:
http://stackoverflow.com/questions/ask
This would equate to the StackOverflow site invoking a controller named ask and displaying its default view, based upon the rules setup for the routing engine.
Read ASP.NET MVC Routing Overview for more information on how ASP.NET MVC routing works.
UPDATE:
For more information on what software and hardware the StackOverflow site was originally built on, then read What Was Stack Overflow Built With?. This is generally still correct, although some of the hardware and amount of each may have changed with an increased user base.

Related

Writing ASP.NET frameworks other than WebForms or MVC?

I want to know what "clean" ASP.NET looks like. For example, I want to build my own framework on ASP.NET, and I don't know what assembly I should include.
All books discussing ASP.NET describe either WebForms or MVC, but none explain the ASP.NET layer of things.
What part of ASP.NET is meant in below picture?
Both WebForms and MVC are implemented through a handler, see the ASP.NET Page Handler and MvcHandler Class on MSDN.
Handlers (MSDN: Introduction to HTTP Handlers) are the most lightweight way to utilize ASP.NET. You get access to an HttpRequest instance that knows everything about the request there is to know.
In a handler, you read this HttpRequest, apply your application logic and write the result throught the HttpResponse member instance that an IHttpHandler's HttpContext parameter in ProcessRequest(HttpContext context) has:
namespace HandlerExample
{
public class MyHttpHandler : IHttpHandler
{
// Override the ProcessRequest method.
public void ProcessRequest(HttpContext context)
{
context.Response.Write("<H1>This is an HttpHandler Test.</H1>");
context.Response.Write("<p>Your Browser:</p>");
context.Response.Write("Type: " + context.Request.Browser.Type + "<br>");
context.Response.Write("Version: " + context.Request.Browser.Version);
}
// Override the IsReusable property.
public bool IsReusable
{
get { return true; }
}
}
}
A lot of ASP.NET, if not all, lives in the System.Web namespace.
ASP.NET WebForms and MVC are built on top of the ASP.NET engine, which basically consists of modules, handlers, and the ecosystem around that.
In fact you can write your own framework by writing modules and handlers. You can write your own code that picks up the request and handles it (handler) or adjust existing messages (modules).
We used NancyFX in several projects and it's definitely worth looking into. Simplicity and performance are amazing. You can host it independently or over the IIS (like asp.net). And it's also cross-platform.

Replacement for ASP.NET Virtual Directory for Multi-tenancy

I am working on an ASP.NET WebForms Application, using ASP.NET 4.5
The Application has multi-tenancy support. Each tenant has an own URL like:
http://myApplication.net/DemoTenant1/
Very simplified in the Login.aspx the application calls this method and translates this URL to an internal ID.
public static string getTenant(HttpRequest request)
{
return = request.Url.ToString();
}
The problem is now, we have more than 200 tenants, for each we need to define an WebApplication which is
a bunch of work :-)
probably very inefficient as an own worker process for each tenant is opend
I am looking for a smart replacement where I stay compatible to the old URLs.
I am looking for an idea how to solve this via URL Routing or maybe to mix WebForms with MVC and add a Login Controller?
Also open to other ideas...
I agree with what Alexander said, the proper way to do this would be with URL Routing.
But... If you are trying to save time...
First, remove all of your web applications;
So get rid of...
http://myApplication.net/DemoTenant1/
http://myApplication.net/DemoTenant2/
http://myApplication.net/DemoTenant3/
And then you need to make sure that typing in the following:
http://myApplication.net/
... takes you to the actual WebApplication you want to use.
Then, in the global.asax file... you need to capture 404 exceptions.
So when someone types in:
http://myApplication.net/DemoTenant1/
... it will throw a 404 exception which you could catch in your global.asax file like this:
void Application_Error(object sender, EventArgs e)
{
string urlData = Request.ServerVariables["SCRIPT_NAME"];
// do some string splitting to get the DemoTenant1 value
// Response.Redirect("~Login.aspx?tenant=DemoTenant1");
}
Its a bit messy but I have done this in the past when I was in exactly the same situation as you. Although, you do now have the routing module built by Microsoft (which I did not have at the time). I am quite sure that you can use the Routing modules within Webforms, without having to use MVC.

AntiForgery implementation in Asp.net Forms

I am developing an httphandler to process some requests in Web Forms (NOT in MVC).
How could I implement Anti Cross Site Scripting (like antiforgery in MVC)?
I want to know mre about the antiforgery mechanism in MVC.
If you can access the Page, you can use the ViewStateUserKey property of the Page. Here is an example of how to do this from within the page, but you will get the idea:
protected void Page_Init(object sender, EventArgs e)
{
// Validate whether ViewState contains the MAC fingerprint
// Without a fingerprint, it's impossible to prevent CSRF.
if (!this.Page.EnableViewStateMac)
{
throw new InvalidOperationException(
"The page does NOT have the MAC enabled and the view" +
"state is therefore vulnerable to tampering.");
}
this.ViewStateUserKey = this.Session.SessionID;
}
While the ViewStateUserKey is pretty safe, there are some short comes with this. You can read more about that here.

What is the most unobtrusive way to add a layer of security for a private beta of website?

Let's say I have an ASP.NET site (MVC in this case) that uses Forms authentication and a typical membership system. The site allows both authenticated and anonymous users.
When I release the site as a private beta I want to add another layer of security on top of the application, like superuser's simple password system, for example. Once a user has passed this layer of security, I still want my forms authentication/membership system in place so beta testers can view the site as authenticated or anonymous users.
What's the most unobtrusive way to achieve this? I'm looking for the easiest solution that will require the least amount of new or modified code. E.g. I don't want to modify every controller to check for a special cookie. There must be a better way...
There's a very similar question here, but it seems the site in question (once public) will only serve anonymous requests, so it doesn't necessarily compare to my situation. This answer suggests ServerFault used some cookie system, but there are no further details about how it might have been implemented.
Implement security at server level, in IIS and add the accounts/passwords in Active Directory of Windows running the IIS server.
You won't need to change any of the code.
Well, I know you don't want to modify your current controllers but here's what I did for a similar behaviour.
I've created a custom ActionFilterAttribute that I've given to every controller that requires to have that specific access check. You can have something like this :
public class CheckBetaAccess : ActionFilterAttribute {
public override void OnActionExecuting(ActionExecutingContext filterContext) {
if (!canAccess) {
filterContext.Controller.ViewData["someViewData"] = "some text";
filterContext.Result = new ViewResult {
ViewName = "the-view-anonymous-users-should-see",
ViewData = filterContext.Controller.ViewData
};
filterContext.Result.ExecuteResult(filterContext);
}
}
}
Then I decorated my controllers :
[CheckBetaAccess]
public class SomeController : Controller {
//....
}

How to have http module on fire events only for specific page types [duplicate]

This question already has answers here:
Exclude certain pages from using a HTTPModule
(3 answers)
Closed 7 years ago.
I have an http module on a sharepoint site and this module instantiates a custom class and add it to the session and does other initial things for my site.
However, I'm noticing that the http module is being called for all request types (.aspx, .js, .png, .jpg).
Is there any way to have an http module only be called for .net specific page types?
In IIS you will set up the handler to be associated with your specific extension so the handler will only be applied to that extension. JavaScript files should not be processed.
I would also have a look at this article is you are looking at integrating your module/handler with SharePoint in any way.
While I do like the ease of deployment of this type of http handler (and the fact that you do not have to deploy a web.config entry for the handler), in cases where you may not want to use the _layouts directory OR you want to have a custom file extension, here is an alternative method that works as well (although it does take one manual configuration step in IIS so it may not be suitable for a "No Touch Deployment")
1) Create your http handler as you normally would for an asp.net application. You can add references to the SharePoint DLLs and interact with the object model since you are in the App Pool.
2) Add and entry into your web.config to register your handler and define the extension you are going to use. IE:
3) Define your custom extension in IIS through the IIS > Web SIte Properties > Home Directory > Configuration > Mappings
In this case, we defined a .proxy extension that the handler will pick up. Our handler is a .NET assembly so we need to add the mapping to route .proxy requests to the .net isapi dll (C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll).. also, make sure you UNcheck the "
From comments on http://msdn.microsoft.com/en-us/library/bb457204.aspx
I've done a bit more research and it seems there is no way to do what I'm intending.
I will have to check the request type and cancel from there.
Thanks everyone for their answers.
D
You can do this in a very lightweight manner using a HttpModule (before making any calls to the expensive SharePoint object model) by checking the extension in the content of the last Uri.Segments
void context_BeginRequest(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
Uri uri = app.Request.Url;
string lastSegment = uri.Segments[uri.Segments.Length-1];
.. check your extension here an do nothing if it doesn't match.
..
}
We use this in our 'TinyURL' implementation for SharePoint to ensure the performance impact for regular URLs is almost 0.
Here is some simple example how to filter requests by extension... the example below exclude from the processing files with the specific extensions.
public class AuthenticationModule : IHttpModule
{
private static readonly List<string> extensionsToSkip = AuthenticationConfig.ExtensionsToSkip.Split('|').ToList();
// In the Init function, register for HttpApplication
// events by adding your handlers.
public void Init(HttpApplication application)
{
application.BeginRequest += new EventHandler(this.Application_BeginRequest);
application.EndRequest += new EventHandler(this.Application_EndRequest);
}
private void Application_BeginRequest(Object source, EventArgs e)
{
// we don't have to process all requests...
if (extensionsToSkip.Contains(Path.GetExtension(HttpContext.Current.Request.Url.LocalPath)))
return;
Trace.WriteLine("Application_BeginRequest: " + HttpContext.Current.Request.Url.AbsoluteUri);
}
private void Application_EndRequest(Object source, EventArgs e)
{
// we don't have to process all requests...
if (extensionsToSkip.Contains(Path.GetExtension(HttpContext.Current.Request.Url.LocalPath)))
return;
Trace.WriteLine("Application_BeginRequest: " + HttpContext.Current.Request.Url.AbsoluteUri);
}
}
In config file specify what extensions should be excluded and initiate the list of extensions in the module.

Resources