English 中文(简体)
发生异常时返回特殊的JsonResult
原标题:Return special JsonResult in case of Exception occurs
public JsonResult Menu() { // Exception }

I need application not to redirect user to the 404 page, but return special JSON result like { "result":1 }.
I wonder, is there any another solution, not try-catching.

最佳回答

您可以实现自己的FilterAttribute,类似于HandleErrorAttribute

HandleErrorAttribute通常在发生错误时进行重定向,但您可以实现返回JsonResult的类似属性。如下所示:

public class CustomHandleErrorAttribute : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        if (filterContext == null)
        {
            throw new ArgumentNullException("filterContext");
        }

        filterContext.Result = new JsonResult
        {
            Data = new { result = 1 },
            JsonRequestBehavior = JsonRequestBehavior.AllowGet
        };
        filterContext.ExceptionHandled = true;
    }
}

然后

[CustomHandleError]
public JsonResult Menu()
{
    throw new Exception();
}

我建议您从CodePlex下载MVC源代码,并检查HandleErrorAttribute的当前实现。它比我上面的粗略实现要微妙得多,你可能想要它的一些功能。

问题回答

暂无回答




相关问题
WebForms and ASP.NET MVC co-existence

I am trying to make a WebForms project and ASP.NET MVC per this question. One of the things I ve done to make that happen is that I added a namespaces node to the WebForms web.config: <pages ...

Post back complex object from client side

I m using ASP.NET MVC and Entity Framework. I m going to pass a complex entity to the client side and allow the user to modify it, and post it back to the controller. But I don t know how to do that ...

Create an incremental placeholder in NHaml

What I want to reach is a way to add a script and style placeholder in my master. They will include my initial site.css and jquery.js files. Each haml page or partial can then add their own required ...

asp.net mvc automapper parsing

let s say we have something like this public class Person { public string Name {get; set;} public Country Country {get; set;} } public class PersonViewModel { public Person Person {get; ...

structureMap mocks stub help

I have an BLL that does validation on user input then inserts a parent(PorEO) and then inserts children(PorBoxEO). So there are two calls to the same InsertJCDC. One like this=>InsertJCDC(fakePor)...

ASP.NET MVC: How should it work with subversion?

So, I have an asp.net mvc app that is being worked on by multiple developers in differing capacities. This is our first time working on a mvc app and my first time working with .NET. Our app does not ...

System.Web.Mvc.Controller Initialize

i have the following base controller... public class BaseController : Controller { protected override void Initialize(System.Web.Routing.RequestContext requestContext) { if (...

热门标签