URLs with slash in the middle of parameters - asp.net

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.

Related

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

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.

Check if string matches url

I've got a string url e.g. "http://localhost:3839/MyController/Statement1/myResult"
I need to do some logic on this i.e. if the url contains MyController/ and /myResult I need to redirect somewhere else.
Whats the easiest way to do this? I'm trying with regex but not sure how to do this.
You can do like below
string strURL=#"http://localhost:3839/MyController/Statement1/myResult";
if(strURL.contains("MyController") || strURL.contains("myResult")
{
//redirect logic here
}
What you could do is create a new Uri instance, which will do the parsing for you. You can create an Uri instance for you URL as follows:
var uri = new Uri("http://localhost:3839/MyController/Statement1/myResult");
You can then use the properties of the Uri instance to extract the different parts of the URI:
Console.WriteLine(uri.AbsolutePath); // outputs "/MyController/Statement1/myResult"
Console.WriteLine(uri.Scheme); // outputs "http"
Console.WriteLine(uri.Host); // outputs "localhost"
Console.WriteLine(uri.Port); // outputs "3839"

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);
}

How do I create a route for matching all paths starting with a given prefix?

In my MVC application I want to create a route such that when a user requests a URL starting with a prefix some specific action is invoked.
For example, I want a route that would map processData{whatever} onto an action so that when a user requests processData, processData.asmx or processDataZOMG or whatever else with processData prefix that action is invoked.
I tried the following route
routes.MapRoute(
#"ProcessData", #"processData*", //<<<< note asterisk
new { controller = #"Api", action = #"ProcessData" } );
but it doesn't match processData and anything with that prefix - route matching falls through and the request is redirected to the main page.
How do I make a route that matches all paths with a specific prefix onto a specific controller-action pair?
Try the following: Update: This solution does not work, please refer to the solution I offer in my comment to this answer.
routes.MapRoute(
#"ProcessData", #"processData/{*appendix}", //<<<< note asterisk
new { controller = #"Api", action = #"ProcessData" } );
You could use route constraints:
routes.MapRoute(
"ProcessData", // Route name
"{token}", // URL with parameters
new { controller = "Api", action = "ProcessData" }, // Parameter defaults
new { token = #"^processdata.*" } // constraints
);

Url helper for full url in asp.net mvc-3

Writing
#Url.Content("~/Something/Something.html")
in razor renders
/AppFolder/Something/Something.html
Is there a way to render the full URL like http://www.something.com/AppFolder/Something/Something.html without atrocious hacks? (like storing the protocol and domain in the AppConfig, and concatenate the string to it)
Is there a helper like #Url.FullPath("~/asdf/asdf") or similar?
See this blog post for the answer.
Basically, all you need to do it include the protocol parameter e.g.
Url.Action("About", "Home", null, "http")
The #Url.RouteURL() does not quiet answer this question. It does work for named routes but falls short for arbitrary virtual paths.
Here is quick helper method that generates full outbound url. You can create overloads for various schemes (http[s]) depending on the degree of control desired.
public static class UrlHelperExtension
{
public static string ContentFullPath(this UrlHelper url,string virtualPath)
{
var result = string.Empty;
Uri requestUrl = url.RequestContext.HttpContext.Request.Url;
result = string.Format("{0}://{1}{2}",
requestUrl.Scheme,
requestUrl.Authority,
VirtualPathUtility.ToAbsolute(virtualPath));
return result;
}
}
For anyone needing to build URLs in WebAPI 2.2 and/or MVC5, this worked for me:
// works in a controller
var requestUri = this.Request.RequestUri;
// just the http/s and the hostname; ymmv
string baseUrl = requestUri.Scheme + "://" + requestUri.Authority + "/";
// build your url for whatever purpose you need it for
string url = baseUrl + "SomeOtherController?id=" + <some_magic_value>;
You can use a helper to produce a full url, including protocol. Note the first lowercase in url.Action.
var url = new UrlHelper(System.Web.HttpContext.Current.Request.RequestContext);
var fullUrl = url.Action("YourAction", "YourController", new { id = something }, protocol: System.Web.HttpContext.Current.Request.Url.Scheme);
Output
https://www.yourdomain.com/YourController/YourAction?id=something

Resources