ASP.NET MVC Use Hyphens in parameter when the raw value has hyphens
I'm writing an MVC app where I want the URL's to be SEO friendly and parameter lookup to be by name rather than id. So for example, instead of having something like this:
/Products/Category/23
I'll have somet开发者_运维问答hing like this:
/Products/Category/Books
And, it seems that the best practice recommendations are to replace spaces with hyphens instead of underscores or %20, so multi-word categories in the example above would be something like this:
/Products/Category/Wall-Decorations
/Products/Category/some-other-name
However, what do we do whenever the parameter's raw value actually contains hyphens? For example, something like
/Products/Category/E-Books
In this case, the hyphen is actually part of "E-books", not a word separator.
So, if I were to:
Products.Where(x => x.Name == parameter.Replace("-",""));
then, "E-books" in the data store would not match "Ebooks" (hyphen replaced from parameter).
The only solution I can come up with is doing something like:
Products.Where(x=> x.Name.Replace("-","") == parameter.Replace("-",""));
that way, "Ebooks" (hyphen replaced in data store) would match "Ebooks" (hyphen replaced from parameter), but that would effectively make it to where in your data store a value with hyphens is the same as a value with no hyphens. And while in this contrived example, "E-books" and "Ebooks" should never exist together, there are other scenarios where the presence of hyphens are important. For example: company names, url's, saved searches that include dashes for date ranges, etc. (not to mention that if you are allowing users to create these names, then we have to plan for everything).
So, I've kind of found a potential workaround for certain specific instances where I can make simplifying assumptions, but does anyone out there have any other suggestions on how to safely handle this for all scenarios?
I am not sure what you mean by "safely handle this for all scenarios". The methodology is sound as long as you always removed spaces in your key (which is a string rather than a numeric - guessing you have a numeric key for your actual derived key (primary key) and a friendly key for the URI?). I would have to know what scenario you see that fits outside of this box.
If some keys must have spaces, then you can replace hyphens with spaces in your code. Is that a scenario you are talking about?
精彩评论