Composite C1 - How do I redirect to a 404 within an InlineMethodFunction - http

I have a Composite site where the URL structure is like so:
site.com/products/1234/product-name
The bold part is the page location. 1234 is the Product ID and then product-name is just a slug.
I register PathInfo and I'm using 1234 to read a SQL Database and return information to show on the site. I'm doing that inside an inline C# function called productDetails which returns an XElement to the XSLT Function.
Sometimes, we will discontinue a product or the ID will not exist in our database. What I'd like to do in those cases is to do one of the following
Return a 404
Redirect to my 404 with a URL
I then want to email out a notice (or at least log the error).
Currently, if the product doesn't exist, I just return an empty <product> element.
I have tried the following code inside the InlineMethodFunction > 'productDetails method, but the Response Object doesn't seem to be available. IDEALLY I want to set the Response Type to 404 instead of redirect. Any ideas?:
public static class InlineMethodFunction
{
public static XElement productDetails( int BulkProductId ) {
ProductContext db = new ProductContext();
var products = db.ProductDetailsByBulkID(BulkProductId).ToList();
if (products.Count < 1)
{
// THIS doesn't work
Response.Redirect("~/404?ProductCode=" + BulkProductId.ToString());
HttpContext.Current.Response.Redirect("~/404?ProductCode=" + BulkProductId.ToString());
// ERROR RETURNED The name 'HttpContext' does not exist in the current context
}
//
// rest of code
//
}
}

As it turns out, I was only able to accomplish this in an External function. Kudos to Pauli Østerø!
For those interested... here's the actual code used:
if(products.Count < 1){
HttpResponse response = HttpContext.Current.Response;
response.StatusCode = 404;
response.Status = "404 Not Found";
//
// Send mail to let someone know
//
}
Rather than redirect, I just set the 404 message and the URL stays intact, but with a 404.

Related

how to read additional parameters in alfresco 5.1.1- aikau faceted search

Custom Search UI will be populated when user selects Complex asset in the Advance search screen drop down(apart from Folders,Contents) where 12 fields will be displayed .So when user clicks search button ,need to read those values and redirect to the alfresco repo files(org/alfresco/slingshot/search/search.get.js).We have already customized these files(search.get.js,search.lib.js) existed in the repository to suit out logic and working fine in 4.2.2;As we are migrating to 511,so we need to change this logic in customized faceted-search.get.js to read these values.How to write this logic in customized facted-search.get.js?
It's not actually possible to read those URL hash attributes in the faceted-search.get.js file because the JavaScript controller of the WebScript does not have access to that part of the URL (it only has information about the URL and the request parameters, not the hash parameters).
The hash parameters are actually handled on the client-side by the AlfSearchList widget.
Maybe you could explain what you're trying to achieve so that I can suggest an alternative - i.e. the end goal for the user, not the specifics of the coding you're trying to achieve.
We will be reading the querystring values something like below in the .get.js file.
function getNodeRef(){
var queryString = page.url.getQueryString();
var nodeRef = "NOT FOUND";
var stringArray = queryString.split("&");
for (var t = 0; t < stringArray.length; t++) {
if (stringArray[t].indexOf('nodeRef=') > -1) {
nodeRef = stringArray[t].split('=')[1];
break;
}
}
if (nodeRef !== "NOT FOUND") {
nodeRef = nodeRef.replace("://", "/");
return nodeRef;
}
else {
throw new Error("Node Reference is not found.");
}
}
It may be help you and we will wait for Dave Drapper suggestion also.

URLs with slash in the middle of parameters

I am creating a MVC 4 application and using the route mapping to route a url like
http://ModelSearch.com/Home/PartDetail/1000-1583-XIR/a
routes.MapRoute("PartDetail", "{controller}/{action}/{id}/{rev}", new { action = "PartDetail" });
There might be id like "1000/1584"
http://ModelSearch.com/Home/PartDetail/1000/1584/b
How do I handle it from new mapRoute? wildcard doesn't work for middle parameter.
You can re arrange your parameter and use the wildcard url segments for Id at the end of your url pattern.
[Route("Home/PartDetail/{rev}/{*id}")]
public ActionResult PartDetail(string rev,string id)
{
return Content("rev:"+rev+",id:"+id);
}
The *id is like a catch anything. So "1000/1584" segment of the request url will be mapped to the id parameter.

asp.net basic routing not working

I'm working on asp.net web forms and i got some issue with routing, following route is not working:
RouteTable.Routes.Add(new Route("{resource}.axd/{*pathInfo}", new StopRoutingHandler()));
RouteTable.Routes.MapPageRoute("category", "en/Product/{ProductName}", "~/en/index.aspx");
url i'm tring is:
http://localhost:5562/en/Product.aspx?ProductName=Laptop
Try http://localhost:5562/en/Product/Laptop as your browser route.
Then, based on your comments, if you want to forbid a value, do this in your code that reads the value, within index.aspx (or product.aspx if you're using that):
string value = Page.RouteData.Values("ProductName"); // get the product being searched for from the URL
List<string> forbiddenValues = new List<string> { "Computer", "BadWord2", "BadWord3" }; // put your forbidden terms in here
if (forbiddenValues.Contains(s, StringComparer.CurrentCultureIgnoreCase)) // case-insensitive
{
// Bad value detect - throw error or do something
MyLiteral.Text = "Bad term found. Cannot continue";
} else
{
// do you database stuff here and get the products
}

RouteCollection Querysting

I am trying to define MapPageRoute on the application global.asax but my problem is that I can not route the specific URL to a physical file with a query string.
For example I want to redirect http://mysite.com/Apple to http://mysite.com/product.aspx?id=95.
What I managed to achieve so far is if a user ask for ./Apple he will be redirected to ./product.aspx but I can not pass the query string.
Looking forward for your comments.
Try this:
if (Page.RouteData.Values["Apple"] != null)
{
int appleID = Convert.ToInt32(Page.RouteData.Values["Apple"]);
Response.Redirect("~/product.aspx?id=" + appleID.ToString(), true);
}

SEO: Duplicated URLs with and without dash "/" and ASP.NET MVC

after reading this article "Slash or not to slash" (link: http://googlewebmastercentral.blogspot.com/2010/04/to-slash-or-not-to-slash.html) on Google Webmaster Central Blog (the oficial one) I decided to test my ASP.NET MVC app.
For example:
http://domain.com/products and http://domain.com/products/ (with "/" in the end), return the code 200, which means: Google understands it as two different links and likely to be a "duplicated content". They suggest to choose the way you want... with or without dash and create a 301 permanent redirect to the preferred way.
So if I choose without dash, when I try to access http://domain.com/products/ it will return a 301 to the link without dash: http://domain.com/products.
The question is, how can I do that with ASP.NET MVC?
Thanks,
Gui
If your using IIS 7 you could use the URL Rewrite Extension ScottGu has a blog post about it here.
Alternatively if you want to do it in code you could inherit from PerRequestTask. Here some sample code the removes the www from an address - this is from Shrinkr:
public class RemoveWww : PerRequestTask
{
protected override TaskContinuation ExecuteCore(PerRequestExecutionContext executionContext)
{
const string Prefix = "http://www.";
Check.Argument.IsNotNull(executionContext, "executionContext");
HttpContextBase httpContext = executionContext.HttpContext;
string url = httpContext.Request.Url.ToString();
bool startsWith3W = url.StartsWith(Prefix, StringComparison.OrdinalIgnoreCase);
bool shouldContinue = true;
if (startsWith3W)
{
string newUrl = "http://" + url.Substring(Prefix.Length);
HttpResponseBase response = httpContext.Response;
response.StatusCode = (int) HttpStatusCode.MovedPermanently;
response.Status = "301 Moved Permanently";
response.RedirectLocation = newUrl;
response.SuppressContent = true;
response.End();
shouldContinue = false;
}
return shouldContinue ? TaskContinuation.Continue : TaskContinuation.Break;
}
}
You would just need to check for the url ending with a / in your code.
** Note this does use a 3rd party dll - System.Web.MVC.Extensibility namespace. **
It dosnt matter really for Google, but what does matter is if both urls'
http://domain.com/products and http://domain.com/products/ show the same page, you also need to watch with windows servers that links to your site like from external pages where the user has typed http://domain.com/PRODUCTS/ will aloso be seen as a diffrent page as the web is case sensitive.
There is away round this with the use of canonical url meta tag, it tell s google what the page name is really, so will avoid duplicate pages which ant really diuplicate
http://googlewebmastercentral.blogspot.com/2009/02/specify-your-canonical.html
you need to check the URI in the INIT event and check the URI to see if it coming in with the slash, if it is, simply do a redirect and add the 301 header to the output response.

Resources