Return HTTP 404 when MVC2 view does not exist 



حمایت از ما | مشهدهاست

Return HTTP 404 when MVC2 view does not exist


حمایت از ما | مشهدهاست

حمایت از ما | مشهدهاست حمایت از ما | مشهدهاست

حمایت از ما | مشهدهاست
`

Return HTTP 404 when MVC2 view does not exist



asked

6 years ago

viewed

1801 times

active

6 years ago


I just need to have the a small CMS-like controller. The easiest way would be something like this:

public class HomeController : Controller {     public ActionResult View(string name) {         if (!ViewExists(name))             return new HttpNotFoundResult();         return View(name);     }      private bool ViewExists(string name) {         // How to check if the view exists without checking the file itself?     } } 

The question is how to return HTTP 404 if the there is no view available?

Probably I can check the files in appropriate locations and cache the result, but that feels really dirty.

Thanks,
Dmitriy.


2010-05-06 10:56:38Z


1:


private bool ViewExists(string name) {     return ViewEngines.Engines.FindView(         ControllerContext, name, "").View != null; } 


2:


The answer from Darin Dimitrov got me an idea.

I think it would be best to do just this:

public class HomeController : Controller {     public ActionResult View(string name) {         return new ViewResultWithHttpNotFound { ViewName = name};     } } 

having a new type of action result:

    public class ViewResultWithHttpNotFound : ViewResult {          protected override ViewEngineResult FindView(ControllerContext context) {             ViewEngineResult result = ViewEngineCollection.FindView(context, ViewName, MasterName);             if (result.View == null)                 throw new HttpException(404, "Not Found");             return result;               }      } 



 اين مطلب بدون دخالت انساني عينا از اين آدرس کپي شده و تمامي مسوليت آن با ناشر اصلي است.

ASP.NET Web Application Message Box
IE9 JavaScript error: SCRIPT5007: Unable to get value of the property 'ui': object is null or undefined
How to Convert DataSet to DataTable
How can I get the CheckBoxList selected values, what I have doesn't seem to work C#.NET/VisualWebPart
Change GridView row color based on condition
What causing this “Invalid length for a Base-64 char array”

How to get current page URL in MVC 3
Read data from SqlDataReader
Get current date only in C#
How to add doublequotes to a string that is inside a variable?
Select method in List<t> Collection
Setting dropdownlist selecteditem programmatically
*