is there any IIS setting require for url rewriting? - asp.net

i have used URL rewriting using global.asax file. url rewriting is working file on local machine but when i made it online its not working.
void Application_BeginRequest(Object sender, EventArgs e)
{
var extension = Path.GetExtension(Request.PhysicalPath).ToLower();
if (File.Exists(Request.PhysicalPath))
{
if (extension == ".html")
{
Response.WriteFile(Request.PhysicalPath);
Response.End();
}
return;
}
var path = Request.Path;
if (!Context.Items.Contains("ORIGINAL_REQUEST"))
Context.Items.Add("ORIGINAL_REQUEST", path);
if (extension == ".html")
{
var resource = UrlRewriting.FindRequestedResource();
var command = UrlRewriting.GetExecutionPath(resource);
Context.RewritePath(command, true);
}
}
url is:ind205.cfmdeveloper.com
when you click on about us ,demo,advertise page it will not display.
so please let me know is there any IIS setting require,
reply me soon
thanks
Samir

I work on url rewriting. I don't think it need any setting in IIS as i work in it and i didn't made any changes in url writing by the way you can see these links.hopefully you get any solution from them.
http://weblogs.asp.net/scottgu/archive/2007/02/26/tip-trick-url-rewriting-with-asp-net.aspx
http://learn.iis.net/page.aspx/496/iis-url-rewriting-and-aspnet-routing/
http://learn.iis.net/page.aspx/517/url-rewriting-for-aspnet-web-forms/
http://www.asp.net/learn/Videos/video-154.aspx
http://www.15seconds.com/Issue/030522.htm
http://urlrewriter.net/
If you got your answer from these links check my answer and also vote it.thanx

I notice that you have .html file that you check for. For html to pass from asp.net processing , you need to declare it (map it) ether on iis ether on web.config

Related

URL Rewriting exceptional case for removing .aspx extension

My scenario is: I have a website which is ASP.NET WebForm. Users can create their own page on my web site, their page url would be something like this: (MyWebsite.com/UserPage). but It is actually: (MyWebsite.com/UserPages.aspx?q=UserPage). It means when you enter the url (MyWebsite.com/UserPage) It rewrites the url and shows you (MyWebsite.com/UserPages.aspx?q=UserPage) (but the address bar is always like (MyWebsite.com/UserPage).
Here's my code in my "UrlRewriting" class:
void context_BeginRequest(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
if (app.Request.Path.Contains("/") && !app.Request.Path.Contains(".") && app.Request.Path.IndexOf("/") == app.Request.Path.LastIndexOf("/"))
{
string userPageTitle = app.Request.Path.Substring(app.Request.Path.IndexOf("/") + 1);
if (!string.IsNullOrEmpty(userPageTitle ))
{
app.Context.RewritePath(string.Format("UserPages.aspx?q={0}", userPageTitle));
}
}
}
Now here's my problem: as I said my project is ASP.NET WebForm, (So, all of pages have .aspx extension) I wanted to remove the .aspx extension in my Urls, I've tried some codes in web.config which were working properly (In normal cases), but In my case, if you enter (MyWebsite.com/UserPage) It will be considering this "UserPage", as "UserPage.aspx". How can I handle this?
I usually do this with Routing which is available in ASP.NET Web Forms 4+.
You register your routes (URL patterns) in Global.asax, and specify which ASPX page will handle that URL.
This example would have UserPage.aspx handle all URLs that weren't otherwise handled by other ASPX pages.
void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.MapPageRoute("UserPageRoute", "{*url}", "~/UserPage.aspx");
}
Then in your UserPage.aspx you can determine the URL requested by looking at the Request.Url object, eg. Request.Url.PathAndQuery.
Note that you may need some extra web.config settings for this to work, eg (to manage extensionless URL requests)...
<configuration>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />

MVC Permanent way to use redirects for HTTP to HTTPS and turn off for Dev Environment

I got this code from here.
Notice I remmed out the part that redirects to ISSExpress 44300 port because I want to use II7.5 on dev box without https.
public class CustomRequireHttpsFilter : RequireHttpsAttribute
{
protected override void HandleNonHttpsRequest(AuthorizationContext filterContext)
{
// The base only redirects GET, but we added HEAD as well. This avoids exceptions for bots crawling using HEAD.
// The other requests will throw an exception to ensure the correct verbs are used.
// We fall back to the base method as the mvc exceptions are marked as internal.
if (!String.Equals(filterContext.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)
&& !String.Equals(filterContext.HttpContext.Request.HttpMethod, "HEAD", StringComparison.OrdinalIgnoreCase))
{
base.HandleNonHttpsRequest(filterContext);
}
// Redirect to HTTPS version of page
// We updated this to redirect using 301 (permanent) instead of 302 (temporary).
string url = "https://" + filterContext.HttpContext.Request.Url.Host + filterContext.HttpContext.Request.RawUrl;
//if (string.Equals(filterContext.HttpContext.Request.Url.Host, "localhost", StringComparison.OrdinalIgnoreCase))
// {
// // For localhost requests, default to IISExpress https default port (44300)
// url = "https://" + filterContext.HttpContext.Request.Url.Host + ":44300" + filterContext.HttpContext.Request.RawUrl;
// }
filterContext.Result = new RedirectResult(url, true);
}
}
Then, in my FilterDonfig.cs I added this. What it does is it only uses the override above if Web.config has "Debug=false", which is what it has in Production. I don't need to run Release in my development environment, and I also don't want configure local IIS to handle SSL. Notice I remmed out the "RequireHttpsAttribute()" and used the new one above.
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
if (!HttpContext.Current.IsDebuggingEnabled)
{
/////filters.Add(new RequireHttpsAttribute());
filters.Add(new CustomRequireHttpsFilter());
}
}
}
Am I doing the right thing? Is this how to make sure SEO is optimized because search bots only keep track of one website? My understanding is that "http" and "https" are considered 2 separate websites by search engines. Am I doing this in the right place? Not sure what other code I am getting in the way of.
===============
I asked my ISP about how to do permanent redirects and suggested this solution and they said:
Dear Customer,
We did not setup redirection. However, we corrected https bind setting in IIS to fix the problem.
I wonder if IIS can do the same thing and that is what they did. I hope I'm in the right forum :)
How about doing this at an IIS level using the URL rewrite module: http://forums.iis.net/t/1153050.aspx?URL+Rewrite+for+SSL+redirection
To turn it off in dev, just set the enabled rule to false in your dev web.config, but enable it for all servers/environments that have HTTPS set up.
I've used it in the past and its worked really well. Saves cluttering your app with code that isn't app related.

How to secure access to SWF file using ASP.NET?

We have a swf file that we want to secure and make available only to authorized users.
I embedded the file in an aspx page and that works fine, since ASP.NET handles the aspx page, I can use ASP.NET authorization features and in the web.config restrict the access to roles="AllowedUsers" for example.
However smart users could still get to the file by accessing directly for example www.mysite/flash.swf. We want to make that kind of access secure.
Any help would be greatly appreciated!
Thanks!
Aristos,
You were right. Last afternoon just before I went home I tried creating a custom HTTP handler. And it worked nice. :-) Thanks for answering +1
public class CustomFlashHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
if (!context.User.Identity.IsAuthenticated)
{
context.Response.Redirect("Default.aspx?ReturnUrl=%2felVideo.aspx");
context.Response.StatusCode = 401;
return;
}
var url = context.Request.CurrentExecutionFilePath;
if (string.IsNullOrEmpty(url)) return;
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("filename={0}", url));
HttpContext.Current.Response.AddHeader("Content-Type", "application/x-shockwave-flash");
HttpContext.Current.Response.WriteFile(url);
HttpContext.Current.Response.End();
}
public bool IsReusable
{
get { return false; }
}
}
Like Aristos said, you have to map ASP.NET to handle .swf files in IIS.
alt text http://www.freeimagehosting.net/uploads/30424ac60a.png
Then add the custom mapping in the application's web.config
<httpHandlers>
<add verb="*" path="*.swf" type="XXXXX.Web.XXXXX.CustomFlashHandler" validate="false" />
</httpHandlers>
1: href=http://www.freeimagehosting.net/>http://www.freeimagehosting.net/uploads/30424ac60a.png
1: a href=http://www.freeimagehosting.net/>http://www.freeimagehosting.net/uploads/30424ac60a.png border=0 alt="Free Image Hosting">
I think that the most easy and fast solution is to Map this extention (.swf) to handle by asp.net.
I do not know if its works, because I do not have done that, but you can give it a try.
One other way is to place this files, somewhere hidden, or with complex name, and use an .ashx file to just read and send them. In the .ashx file you need to set the correct Response.ContentType for the flash, and just read and send the correct file.

Response.Redirect to a UNC path

I'd like to redirect the user to a directory on a file server using its UNC path. I've tried using something like the following but I just get a 404 error.
Response.Redirect(#"file:\\fileserver\data\");
What's the correct syntax to make this work?
You don't quite have the file protocol identifier correct.
Try:
string location = String.Format("file:///{0}", #"\\fileserver\data\");
Response.Redirect(location, true);
I'm not sure about the Response.Redirect method, but you can always write the file for download by the user using Response.WriteFile.
This link might help: http://support.microsoft.com/kb/307603/EN-US/
Code Snippet from above link:
private void Page_Load(object sender, EventArgs e)
{
//Set the appropriate ContentType.
Response.ContentType = "Application/pdf";
//Write the file directly to the HTTP output stream.
Response.WriteFile(#"\\server\folder\file.pdf");
Response.End();
}
file:////server/directory
Or, create a virtual directory in your Website and map it to a path, like /data/

Why my httpwebrequest post to myhandler.ashx is rejected with status code 401

I've already written an HTTPHandler that gets POSTed from a ColdFusion page and it works successfully; now, I am trying to write a web application in ASP.NET so I can post a form to the .ashx handler from an .aspx page.
Application Trace (trace.axd) shows the following as my last 3 entries:
2 8/14/2009 1:53:56 PM /Default.aspx 200 GET View Details
3 8/14/2009 1:54:04 PM /Default.aspx 200 POST View Details
4 8/14/2009 1:54:13 PM /UploadHandler.ashx 401 POST View Details
I have a breakpoint in my .ashx file but it is never reached (I guess because of the 401 status code). Here is the snippet of code from the default.aspx trying to POST to the handler:
protected void UploadHandlerButton_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
try
{
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(BuildFormData());
string baseAddress = "http://" + Environment.MachineName;
string pathInfo = Page.ResolveUrl("UploadHandler.ashx");
string URI = baseAddress + pathInfo;
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(URI);
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
Stream newStream = myRequest.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
}
catch (Exception someError)
{
LogText("FAILURE: " + someError.Message);
}
}
}
Here is a snippet of code from the UploadHandler.ashx file (but this doesn't appear to be reached):
public void ProcessRequest(HttpContext context)
{
string returnURL = context.Request.ServerVariables["HTTP_REFERER"];
string message;
message = UploadFile(context);
StringBuilder msgReturn = new StringBuilder(returnURL);
msgReturn.Append("?n=");
msgReturn.Append(HttpUtility.UrlEncode(TRIMrecNumAssigned));
msgReturn.Append("&m=");
msgReturn.Append(HttpUtility.UrlEncode(message));
context.Response.Redirect(msgReturn.ToString());
}
Both default.aspx and UploadHandler.ashx are in the root of a virtual directory on my localhost; the directory security is currently set to "Anonymous access" CHECKED and "Integrated Windows authentication" CHECKED.
When I click the "View Details" link on the trace.axd display, I see all the data in the Forms collection that I expect to see and hope to process but this 401 seems to be stopping everything. I could post the code for my little function called BuildFormData() if useful.
EDIT: Revised handler as follows (has had no effect; same error occurs):
public void ProcessRequest(HttpContext context)
{
//-----------------------------------------------------------------------------------------
// the remainder of this block is alternative to the .Redirect and is useful for debugging.
context.Response.ContentType = "text/html";
//context.Response.Write(TRIMrecNumAssigned);
//context.Response.Write("<p>");
//context.Response.Write(msgReturn);
context.Response.Write("<H1>Trim - Kerberos Prototype for ColdFusion consuming pages</h1>");
HttpContext.Current.Trace.IsEnabled = true;
HttpContext.Current.Trace.Write(null);
HttpContext.Current.Trace.Write("-------");
HttpContext.Current.Trace.Write(context.Request.Form["txtTrimRecordType"]);
HttpContext.Current.Trace.Write(GetUserInfo());
HttpContext.Current.Trace.Write("-------");
HttpContext.Current.Trace.Write(null);
using (Html32TextWriter htw = new Html32TextWriter(context.Response.Output))
{
typeof(TraceContext)
.GetMethod("Render", BindingFlags.NonPublic | BindingFlags.Instance)
.Invoke(HttpContext.Current.Trace, new object[] { htw });
}
}
Have you tried turning off Integrated Windows Auth and just leaving anonymous checked? Does it make a difference?
Your answer: "I think it made things worse because now I cannot even browse to default.aspx. I get this: HTTP 401.3 - Access denied by ACL on resource Internet Information Services"
My response: This is actually a good thing. This means we're getting closer to what is going on. If you're getting that error message and the only thing you have enabled is anonymous authentication via IIS, that means that the ASP.NET impersonation user doesn't have NTFS permissions on the files in question.
I'm not sure if you are on XP or Win 2k3, but now you want to check and make sure that either the ASPNET (XP) or Network Service (Win 2k3) users have at least read access on the files in question. Make sure that user has at least that level of access and then let me know how it goes.
Update: I don't know why I didn't think of this before. You may need to set credentials on your HttpWebRequest. To use the credentials of the current user, try adding this to your request.
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(URI);
myRequest.Credentials = CredentialCache.DefaultCredentials;
If you need to add different credentials you can try Network Credentials
There's a good explanation of credentials here.
Hope this helps.
Looking at your ProcessRequest(), you do the following:
string returnURL = context.Request.ServerVariables["HTTP_REFERER"];
Based on how you are calling it with HttpWebRequest, this variable will be null. Then when you create your msgReturn, it will look something like this:
?n=XXX%m=YYY
When you redirect to this URL, it will probably not be found which is what is returning the 401.

Resources