What is the simplest way to return different content types based on the extension in the URL? - asp.net-mvc

I'd like to be able to change the extension of a url and recieve the model in a different format.
e.g. if
/products/list
returns a html page containing a list of products, then
/products/list.json
would return them in a json list.
Note: I like the simplicity of the ASP.NET MVC REST SDK, it only requires about 5 lines of code to hook it in, but the format is specified as a query string parameter i.e. /products/list?format=json which is not what I want, I could tweak this code if there are no other options, but I don't want to reinvent the wheel!

I wrote a blog post that shows one possible example. It's a tiny bit complicated, but might work for your needs.
http://haacked.com/archive/2009/01/06/handling-formats-based-on-url-extension.aspx

You should be able to just use routes in conjunction with the rest sdk

If you have the flexibility to drop Apache or something similar in front of your service, you can always use mod_rewrite to rewrite an external http://products/list.json into http://products/list?format=json which your framework can render more easily.

Instead of "list.json", you could choose "list/json" and use a route like
{controller}/{action}/{id}
Then ProductController.List would be called, with an ID parameter of "json". The .List() action then would decide whether or not to return an HTML view or JSON content.

Related

Using optional parameters in Umbraco 7 Urls

Am new to using Umbraco. I need to create Urls with an an optional parameter on the end e.g.
mysite.com/people/john
mysite.com/people/jane
etc
however by default Umbraco appears to require a separate page for each person. Is there a built method in Umbraco that will allow me to define the last part of the Url as an optional parameter or do I have to write a custom route for it?
Thanks
You have a couple of options here.
Use IIS URL Rewriting to rewrite your URLs under the hood and rewrite /people/john to /people/?person=john say. Then you can pick up the person from the query string on the page.
Write a custom URL Finder that looks for the URLs and does some stuff under the hood, like get the people page, and then set a context item with the person name in for you to use in your views etc.
You could write a custom route for it. Custom routing in Umbraco is slightly different to in normal MVC. Here is a blog post detailing how you can do it: http://shazwazza.com/post/custom-mvc-routes-within-the-umbraco-pipeline/

Rails 3 - Friendly params in url (GET)

I have a rails 3 app and now i implementing filter for my catalog. Filters form pass data to controller through GET request. As a result i have link like this in my browser after i submit
my form (apply search):
http://localhost:3001/shoes?filter%5BShoeBottomType%5D%5B%5D=2&filter%5BShoeClassification%5D%5B%5D=1&filter%5BShoeClassification%5D%5B%5D=2&filter%5BShoeElation%5D%5B%5D=3&filter%5BShoeElation%5D%5B%5D=4&filter%5BShoeElation%5D%5B%5D=5&filter%5BShoeLiningColor%5D%5B%5D=2&filter%5BShoeLiningColor%5D%5B%5D=3&filter%5BShoeLiningColor%5D%5B%5D=4&filter%5BShoeTopColor%5D%5B%5D=1&filter%5BShoeTopColor%5D%5B%5D=2&filter%5Bonly_action%5D%5B%5D=1&page=2
Is there a way to do URL more beautiful?
PS i dont want use POST request, because I read that it is bad for SEO
TLDR: just leave it.
HTML forms serialize in a straightforward manner; the parameters are named after the HTML elements. The actual issue here is how the form elements are named. It looks like they have names like filter[ShoeBottomType][]; look into your HTML to see the name attributes. Since you're in Rails, I'm guessing you having a filter hash passed to your Rails controller method as a single argument, and since Rails expects hashes to use a certain URL format for hashes and arrays (it has to know how to deserialize it from the request), the form helper writes the form that way. And yours is especially complicated because the hash values are arrays, hence the extra set of brackets. Then it's URL encoded and you end up with an ugly mess.
You could avoid some of this problem by passing the inputs individually back to the controller instead of as a big hash. Something like:
def index
shoe_bottom_types = params[:bottom_types]
shoe_classifications = params[:classifications]
shoe_elations = params[:elations]
...
which will get you to: /shoes?bottomTypes[]=1&bottomTypes[]=2.... That doesn't seem much better, and now your controller is all gross. And I don't see how you're going to get rid of the brackets entirely if you want to have more than one of the same filter. I guess you could get crazy and do your own parsing in your controller, like breaking apart shoeBottomTypes=1|2, but then you'll have to do your own form serialization too. Again, just not worth it.
Backing up for a sec, the SEO stuff doesn't make much sense. Search engines won't fill out your form; they just follow links. The real reason you should use GET is that (presumably), submitting your form doesn't have side effects, since it's just a search. See here; it's important to use the right HTTP methods. If you use POST, you'll get weird warnings on reloads and you won't be able to bookmark the search.
Backing up even further, why do you care, especially now that SEO is out of the picture? Just as a quick demo, I did a google search for the word "thing" and this was the URL:
https://www.google.com/#hl=en&output=search&sclient=psy-ab&q=thing&pbx=1&oq=thing&aq=f&aqi=g2g-s1g1&aql=1&gs_sm=3&gs_upl=764l1877l0l1980l6l6l0l0l0l0l89l432l5l5l0&bav=on.2,or.r_gc.r_pw.r_cp.r_qf.,cf.osb&fp=220ef4545fdef788&biw=1920&bih=1086
So URLs for form submissions can be long. The user won't even look at it.
The only possibility I can think of for why you'd care about the length/ugliness of your URL here is that you want, separately from the form, to create links to certain searches. There are several ways to handle that, but since I don't know whether that's relevant to you, I'll let that be a follow-up.
So bottom line, it looks like I'd expect, and trying to fix it sounds ugly and pointless.
If you do not want to use a POST request, then there is no other way then to put the form values in the URL -- they have to get to the server one way or another.
On the other hand however, I do not see why doing a POST would be bad for SEO and I would love to see the article that stated so.
My suggestion is that you could add some custom routes to beautify your urls.
For example :
http://localhost:3001/shoes/Type/2/Classification/1,2/Elation/3,4,5/LiningColor/2,3,4/TopColor/1,2/only_action/1/page/2
This is far much shorter than your initial URL ;)
The counterpart is that, as far as I know, you have to use always the same order for params in your url.
The routing rule is the following :
match "shoes/Type/:type/Classification/:classification/Elation/:elation/LiningColor/:liningcolor/TopColor/:topcolor/only_action/:only_action/page/:page" => "shoes#show"
You can retrieve the passed values in params array. You have to split the string containing , in order to retrieve the multiple values.

How to get current page Url in MVC

I am writing a web app that has to deal with urls containing hash character ("#").
I am using MVC 1 with ASP.NET 3.5 (VS 2008).
My urls are like this one:
www.mysite.com/token/?name1=value1&#&name2=value2
My issue is that I cannot find a method to get the original URL, but only get the substring before the hash character:
www.mysite.com/token/?name1=value1&
I used the MVC methods provided from the class HttpRequestBase.
Anyone can suggest me an alternate method to get the entire url?
Thank you, this is my very first question!
PS: I think maybe I have to encode my hash character, isn'it?
You cannot access anything after the # from the server-side - this is all Client-side. You will need to find another way to pass the information you want through to the server.
If you are posting, you can do this with hidden fields. If you are using ajax posts, you can pass the data within the model.

How to make ASP.NET MVC create lowercase urls (action links)?

I know this question has been asked many times. But people suggest creating custom derived route classes, or writing lowercase everywhere in code (for action links) which is a really dirty way (what if I just decide to make'em all Pascal Cased again? changing hundreds of links?), or they suggest to create HTML helpers to do that (which is not a bad answer). But isn't there a more simple way? I mean something like setting some configuration in web.config file, or using an HttpModule or something else which is both simple, and centralized?
Apart from the options you have already listed, I can think of no other way of producing this result.
In short, the URL needs to be processed by 'something', be it .ToLower(), a Helper Method or HTTPModule.
In most of our applications, we use a Global Static method that performs actions on the desired URI and returns the result.
The following will allow that.. http://mvccoderouting.codeplex.com/ - and much more besides.

How to access AJAX hash values in ASP.NET MVC?

I'm considering using the hash method to create static urls to content that is managed by ajax calls in a Asp.Net MVC. The proof of concept i'm working on is a profile page /user/profile where one can browse and edit different sections. You could always ask for the following url /user/profile#password to access directly to you profile page, in the change password section
However, i'm wondering if i'm not starting this the bad way, since apparently i can't access the part after the hash in any way, except by declaring a route value for the hash in global.asax. So i'm wondering if this is the right way to access this part of the url?
Am i supposed to declare a route value, or is there another way to work with hash values (a framework, javascript or mvc)?
Edited to add:
In pure javascript, i have no problem using the window.location.hash property, i'm not sure though how standard it is in today's browsers, hence the question about a javascript framework/plugin that would use it.
The thing is that the part that follows the hash (#) is never sent to the server into the HTTP request so the server has absolutely no way of reading it. So no need to waste time in searching for something that doesn't exist.
You could on the other hand tune your routes to generate links that contain the hash part so that client scripts can read it.
Send the hash value document.location.hash as a parameter to the controller action of your choice.
This can be done in the code if needed...
RedirectResult(Url.Action("profile") + "#password");
should work fine

Resources