Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public FooViewModel Get()
- {
- if (HttpContext.Current == null)
- {
- return new FooViewModel();
- }
- var currentContext = new HttpContextWrapper(HttpContext.Current);
- // resolve actual view model.
- throw new HttpException(404, "HTTP/1.1 404 Not Found");
- currentContext.Response.End();
- public class HomeController : Controller
- {
- public FooViewModel Foo { get; set; }
- public ActionResult Index()
- {
- ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
- return View();
- }
- public class RequiresModelAttribute : ActionFilterAttribute
- {
- private readonly string _modelName;
- public RequiresModelAttribute(string modelName)
- {
- _modelName = modelName;
- }
- public override void OnActionExecuting(ActionExecutingContext filterContext)
- {
- var property = filterContext.Controller.GetType().GetProperty(_modelName);
- var model = property.GetValue(filterContext.Controller);
- if (model == null)
- {
- filterContext.Result = new HttpStatusCodeResult(404);
- }
- }
- }
- public class HomeController : Controller
- {
- public FooViewModel Foo { get; set; }
- [RequiresModel("Foo")]
- public ActionResult Index()
- {
- ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
- return View();
- }
- }
- public class HonorHttpExceptionAttribute : ActionFilterAttribute
- {
- public override void OnActionExecuting(ActionExecutingContext filterContext)
- {
- var httpException = filterContext.HttpContext.AllErrors.FirstOrDefault(x => x is HttpException) as HttpException;
- if (httpException != null)
- {
- filterContext.Result = new HttpStatusCodeResult(httpException.GetHttpCode());
- }
- }
- }
- public static void RegisterGlobalFilters(GlobalFilterCollection filters)
- {
- filters.Add(new HandleErrorAttribute());
- filters.Add(new HonorHttpExceptionAttribute());
- }
- public ActionResult Index()
- {
- ViewBag.Message = "Welcome to ASP.NET MVC!";
- Get();
- return View();
- }
- public int Get()
- {
- throw new HttpException(404, "HTTP/1.1 404 Not Found");
- // we don't need end the response here, we need go to result step
- // currentContext.Response.End();
- }
- protected override void OnException(ExceptionContext filterContext)
- {
- base.OnException(filterContext);
- if (filterContext.Exception is HttpException)
- {
- filterContext.Result = this.HttpNotFound(filterContext.Exception.Message);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement