-1

I have a .NET MVC application. So far, each page is accessed via a controller.

Now I want to direct access some cshtml files such as

http://example.org/file/abc.cshtml.

Though having .cshtml file extension, these are just pure html snippets.

How can I access these files without going through any controller.

Thanks and regards.

curious1
  • 14,155
  • 37
  • 130
  • 231
  • 2
    Since they are just html, why not use .html extension and call directly: www.domain.com/file/abc.html ? – Thiago Custodio Aug 14 '14 at 19:21
  • These files were created in another project, I cannot modiyy them. Thanks for chiming in! – curious1 Aug 14 '14 at 19:23
  • 1
    You could either copy the contents of that .cshtml file to your own or render it as part of another cshtml file using @Html.Partial('ViewName') –  Aug 14 '14 at 19:30
  • 1
    This question's answer might be helpful to you: http://stackoverflow.com/questions/17309704/cshtml-files-not-working-iis. Also, see the related questions on that post as well. – Josh Darnell Aug 14 '14 at 19:42

1 Answers1

1

I would probably make a controller with an action which accepts a view name, grabs the view from the file system, and returns it as a FileResult with the mimetype text/html. You'd probably want the controller to have a hardcoded whitelist of html-fragment files, to reduce the chances that you're opening up a way for people to browse around your folder structure.

You could also look into configuring IIS to serve .cshtml files from some directories, but I'd be more concerned about accidentally opening up too much using that method.

Steve Ruble
  • 3,875
  • 21
  • 27
  • Steve, thanks for pointing me to the solution. I got it working just as you said. Cheers! – curious1 Aug 14 '14 at 21:17
  • 1
    @curious1, you might want to put an `OutputCacheAttribute` (http://msdn.microsoft.com/en-us/library/system.web.mvc.outputcacheattribute(v=vs.118).aspx) on the action method, so that you won't be building and running a whole controller on each request for what is really a static file. – Steve Ruble Aug 14 '14 at 21:33
  • Steve, thanks for following up me. I use "return new FilePathResult(fileName, "text/hmtl")" for return in my controller. I want to add encoding. Any pointer for that? The html snippet has spanish characters and they look distorted in pages. – curious1 Aug 15 '14 at 00:13
  • I did `return new FilePathResult(fileName, "text/html; charset=utf-8")`, and it is still not working. – curious1 Aug 15 '14 at 02:47
  • @curious1, I think you can set `Response.ContentEncoding = Encoding.UTF8`. That may not fix your problem, however - you may need to escape the Spanish characters to HTML entities (http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Character_entity_references_in_HTML) – Steve Ruble Aug 15 '14 at 14:01