Redirect permanently 301 in blogengine.net (global.asax) - blogengine.net

i want to redirect my old address www.informarea.it/BlogEngine to new address www.informarea.it...
*my global.asax of blogengine.net is *
void Application_BeginRequest(object source, EventArgs e)
{
HttpApplication app = (HttpApplication)source;
HttpContext context = app.Context;
// Attempt to perform first request initialization
FirstRequestInitialization.Initialize(context);
}
*can i make to apply the code of redirect permanently? *
if (app.url.ToString().ToLower().Contains("http://www.informarea.it/BlogEngine"))
{
HttpContext.Current.Response.Status = "301 Moved Permanently";
HttpContext.Current.Response.AddHeader("Location",url.Replace("http://www.informarea.it/blogengine", "http://www.informarea.it"));
}
Can Someone help me?
thank you very much
Fabry

This should redirect any query where the path starts with /BlogEngine to the same url with the /BlogEngine removed.
if(Request.Url.PathAndQuery.StartsWith("/BlogEngine", StringComparison.OrdinalIgnoreCase)) {
Response.RedirectPermanent(Request.Url.PathAndQuery.Substring(11), true);
}
Pros:
Gives a 301 Redirect like you requested
Keeps the rest of the path and query string intact for the following request
Cons:
Requires .net 4.0 (Version 2.7 of BlogEngine is targeted at 4.0 so I don't think this will be an issue.)

Related

appharbor force HTTPS for static files

I have a requirement to ensure all traffic on my website is redirected to HTTPS if it is requested over HTTP. When we deploy the site to appharbor, we use the custom RequireHttpsAttribute which works well for our MVC controllers.
However we also want to force any request for static files (images, stylesheets, javascript) via HTTP to be sent to HTTPS. Trying it using the web.config rewrite rules ends up in a redirect loop due to the load balancer sending https request to the web server as http.
Does anyone have any ideas on how to achieve this?
After receiving a reply from appharbor support, one of their suggestions was to implement code similar to the custom RequireHttpsAttribute for static files as well.
So I created a class called HttpRequestModule, and set it up to run for all requests (runAllManagedModulesForAllRequests set to true) I was able to force any direct requests to HTTP urls to redirect to HTTPS.
class HttpRequestModule : IHttpModule
{
public void Init(HttpApplication app)
{
app.BeginRequest += new EventHandler(CheckHttpRequest);
}
private void CheckHttpRequest(object sender, EventArgs a)
{
if (app.Context.Request.IsSecureConnection) return;
if (app.Contact.Request.IsLocal) return;
if (string.Equals(app.Context.Request.Headers["X-Forwarded-Proto"],
"https",
StringComparison.InvariantCultureIgnoreCase))
{
return;
}
var secureUrl = "https://" + app.Context.Request["HTTP_HOST"] + HttpContext.Current.Request.RawUrl;
app.Context.Response.Redirect(secureUrl);
}
}

Get "time of upload started"

I'm developing a WebAPI service in which you can upload a file. The Action looks something like this:
[HttpPost]
public async Task<IHttpActionResult> PostAsync(byte[] content)
{
var now = DateTime.UtcNow;
}
The client which are using the WebAPI also provides a timestamp as header which is used together with some HMAC-stuff to authenticate. One part of the auth check is to validate the timestamp. We parse the timestamp and checks if it is +/- 5 minutes from now. If not then the auth fails.
It works great for all our API calls except this upload API (in some cases). The problem is that sometimes a user uploads a large file over a slow connection and therefore it takes more than 5 minutes to upload the file and the point in time where we check is AFTER the whole file has been uploaded.
Therefore:
Can we somehow do the HMAC check BEFORE the whole file is uploaded? (the file itself (HTTP Content) is not used in the HMAC check). Today we are using an ActionFilter.
Can I get the "time of request" (first byte arrived or whatever) in my Action code?
Thanks!
So, after some investigation I came up with a much better solution:
Use a HTTP Module to do the actual HMAC authentication.
After reading this blog post (http://blogs.msdn.com/b/tmarq/archive/2007/08/30/iis-7-0-asp-net-pipelines-modules-handlers-and-preconditions.aspx) I got a much better understanding of how IIS Works.
I decided to use a HTTP Module which is invoked before the MVC Action.
The code ended up like this:
public class HmacModule : IHttpModule
{
public void Init(HttpApplication context)
{
EventHandlerTaskAsyncHelper taskAsyncHelper = new EventHandlerTaskAsyncHelper(Authenticate);
context.AddOnBeginRequestAsync(taskAsyncHelper.BeginEventHandler, taskAsyncHelper.EndEventHandler);
}
private async Task Authenticate(object sender, EventArgs e)
{
var context = ((HttpApplication)sender).Context;
var request = context.Request;
var authResponse = await CheckAuthentication(request);
if (!authResponse.HasAccess)
{
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
context.Response.StatusDescription = authResponse.ErrorMessage;
if (authResponse.Details != null)
context.Response.Write(authResponse.Details);
context.Response.End();
}
}
}
I hope this helps others in the same situation...

Can't get ASP.NET Web API 2 Help pages working when using Owin

I've installed the correct package for Web Api 2
Install-Package Microsoft.AspNet.WebApi.HelpPage -Pre
But the help area is not being mapped and is returning 404 (Web Api working fine). I'm using Microsoft.Owin.Host.SystemWeb as the host. Below is my Startup code.
public class Startup
{
public void Configuration(IAppBuilder app)
{
//Required for MVC areas new HttpConfiguration() doesn't work with MVC
var config = GlobalConfiguration.Configuration;
AreaRegistration.RegisterAllAreas();
WepApiStartup.Configure(config);
app.UseWebApi(config);
}
}
GlobalConfiguration.Configuration is web host specific HttpConfiguraiton, which should only be used with web host scenario. Use it with OWIN host will cause unexpected issues.
Please use the following code instead:
public class Startup
{
public static HttpConfiguration HttpConfiguration { get; private set; }
public void Configuration(IAppBuilder app)
{
HttpConfiguration = new HttpConfiguration();
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(HttpConfiguration);
app.UseWebApi(HttpConfiguration);
}
}
Replace all GlobalConfiguration.Configuration with Startup.HttpConfiguration in the project include help page files.
Found the solution after a lot of digging/trial and error. The issue is well described here: http://aspnetwebstack.codeplex.com/discussions/453068
UseWebApi and UseHttpMessageHandler don't call Next OWIN's middleware other than for 404. This means if you use UseWebApi that's it, Next is never called therefore you can't use it with any other middleware (Nancy or Web Api Help pages for example).
Thanks to #aliostad patch:
https://github.com/aliostad/CacheCow/blob/master/samples/UsingCacheCowWithNancyAndOwin/HttpMessageHandlerAdapterModified.cs#L43
You can get it working as expected. I hope the team merge the pull request for this as UseWebApi breaks the Owin design goals IMO.
Update 13 Feb 2014
I've written an Owin extension to workaround this:
internal static void UseWebApiAndHelp(this IAppBuilder app, HttpConfiguration config)
{
WepApiStartup.Configure(config);
app.UseHandlerAsync((request, response, next) =>
{
if (request.Path == "/") //app.Map using a regex exclude list would be better here so it doesn't fire for every request
{
response.StatusCode = 301;
response.SetHeader("Location", "/Help");
return Task.FromResult(0);
}
return next();
});
// Map the help path and force next to be invoked
app.Map("/help", appbuilder => appbuilder.UseHandlerAsync((request, response, next) => next()));
app.UseWebApi(config);
}
Update 01 July 2015
You can also host the help pages using WebApi instead of MVC, which is great for self host http://blogs.msdn.com/b/yaohuang1/archive/2012/12/20/making-asp-net-web-api-help-page-work-on-self-hosted-services.aspx
Update 10 September 2015
For Web Api I tried #hongye-sun answer and it works too, follow what #gspatel says by changing HelpPageAreaRegistration.RegisterArea and the HelpController's constructor. My workaround works as well so pick whatever one works best for your situation.
However I'm still getting the issue when using UseWebApi with other middleware and it not invoking Next() (seems to only happen when using IIS not self host). I've found my workaround of mapping the path and forcing next to be invoked is a valid workaround for all Owin middleware Nancy, Simple.Web etc.
Update 13 Jan 2016
I've developed Owin middleware to generate the ASP.NET Web API Help pages we know and love that completely solves this problem. My blog post explains the background to this issue in detail

Configuring IIS 6.0 to run an MVC3 application

Configuring IIS 6.0 to run an MVC3 application
I think I have a configuration issue on my IIS 6 server and I'd like to see if there's anything I've missed.
The problem that I'm having is that anytime when a RedirectToAction("Index", "Home") is executed (e.g. in a method that returns an ActionResult) I would expect that I would be returned to:
http://servername.domain.com/virtualdirectoryname
However, instead I get redirected to:
http://servername.domain.com/virtualdirectoryname/virtualdirectoryname
That is a second instance of the virtualdirectoryname appended to the end of the URL and can't figure out why - this URL will of course yield a 404 resource not found error. I written and deployed several MVC3 applications both in corporate intranet and public internet environments and can't figure out what I've done wrong. My global.asax.cs seems ok -
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
if (HttpContext.Current.User != null)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
if (HttpContext.Current.User.Identity is FormsIdentity)
{
FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
FormsAuthenticationTicket ticket = id.Ticket;
// Get the stored user-data, in this case, our roles
string userData = ticket.UserData;
string[] roles = userData.Split(',');
HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(id, roles);
}
}
}
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
}
The Application_AuthenticateRequest handles the storing of the roles for logged on users, but other than that, it seems pretty vanilla. The only think I can think of is that I've somehow messed up the virtual directory.
Prior to performing any of these steps, I had verified that MVC3 and v4.0 of the .NET framework were installed on the server. There are also other ASP.NET 4.0 applications on this server that have been running without incident. There is also an MVC2 application (MVC2 is also installed) running on this server and has been running without incident.
I created a virtual directory off of the main "default site" using the IIS manager.
Setup appropriate permissions on the folder that this virtual directory points to. Tested with a quick "Hello, World" index.html file.
Copied the application from my development PC where the application works as developed to the folder described in #2.
Updated the Web.Config file, editing the connection strings to point to the test database server; I had also verified these connection strings on my development PC.
Open the web browser and hope for the best.
Any assistance is greatly appreciated.
Thanks!
I think what you may be seeing is:
http://servername.domain.com/virtualdirectoryname/applicationname
If you have named your virtual directory the same name as your application then I could see how that could confuse you. If you had no virtual directory and just your application at the root of the Default Web Site you'd be seeing:
http://servername.domain.com/applicationname
Is your virtual directory the same name as your application name? If so, that is why you see this.

Sitecore Extranet login and PDF converter or Webclient

I'm having a problem using Winnovatives PDFConverter on pages that are protected by Extranet security (which is based on ASP.Net Membership).
I've tried several different approaches, but the following I can get to work on my local machine, but not anywhere else.
Code for login page, this code should bypass the login process for:
// check that the current "user" isn't logged in and is the Winnovative UserAgent
if (!Sitecore.Context.IsLoggedIn && Request.UserAgent.Contains(".NET CLR"))
{
//Login with a dummy user I've created
Sitecore.Security.Authentication.AuthenticationManager.Login("extranet\\pdf", "pdf", true);
//redirect to former page
}
The page that generates the PDF uses this code:
private void PDFPrint(string url)
{
PdfConverter pdfConverter = new PdfConverter();
pdfConverter.LicenseKey = "our license";
url = Request.Url.Scheme + "://" + Request.Url.Host + url;
byte[] downloadBytes = pdfConverter.GetPdfFromUrlBytes(url);
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.AddHeader("Content-Type", "binary/octet-stream");
response.AddHeader("Content-Disposition", "attachment; filename=" + Sitecore.Context.Item.Name + ".pdf" + "; size=" + downloadBytes.Length.ToString());
response.Flush();
response.BinaryWrite(downloadBytes);
response.Flush();
response.End();
}
The Exception I'm getting is this:
"Could not get the metafile from url. Could not get image from url.The URL is not accessible.."
I've also tried this trick from the Winnovative FAQ to no avail:
http://www.winnovative-software.com/FAQ.aspx#authenticationQ
I've also tried to use WebClient or HttpWebRequest to retrieve the content.
But nothing I do seems to work other than locally.
Basically I want to create a way of either getting Winnovatives converter to use the current logged in user, my custom "pdf" user og some other way of getting the html from the response.
I hope this question isn't too vague, but I find it kinda hard to ask. But basically I want to get some html content from a page on a Sitecore solution I control, which is protected by Sitecore normal Extranet security. This html content should be in string or byte[] format.
Help me Stackoverflowers, you're my only hope! :P
I contacted Sitecore to ask if they had a solution.
Their solution was to create a Processor that would set an active user based on some criteria.
This is the code I made for my site (it's probably not the best solution as UserAgent can be spoofed):
public class MyResolver : HttpRequestProcessor
{
// Methods
public override void Process(HttpRequestArgs args)
{
var userAgent = args.Context.Request.UserAgent ?? "";
SiteContext site = Sitecore.Context.Site;
if (site.Name == "site_name_in_webconfig" && userAgent.Contains("this_should_only_be_in_thepdfcreators_userAgent"))
{
Sitecore.Security.Accounts.User pdfuser = Sitecore.Security.Accounts.User.FromName("extranet\\theUser", true);
AuthenticationManager.SetActiveUser(pdfuser);
}
}
}
and then add the following to the web.config, before the UserResolver:
<processor type="Namespace.MyResolver, Assembly" />
I hope this will help some others out there.
I've found a similar issue on the ASP.NET forums and the answer to that was to use a newer version of the PDF tool: SessionState Problems ?

Resources