开发者

How to overload Json in asp.net mvc for custom results

开发者 https://www.devze.com 2023-02-05 12:41 出处:网络
I want to create a special json format for all actions that return a Json result. I\'d like to do something like this:

I want to create a special json format for all actions that return a Json result. I'd like to do something like this:

//Returning content, ok status, etc.
{value: { name: "Lol coder", id : "2"} }

//If exception
{exception : {loc: "MyProj.Web.AuthController", type: "email_not_found", email: "lolCoder@hotmail.com"}}

I hope this is clear.

ASP.NET MVC Action:

private bool noError = tru开发者_如何学JAVAe; //used to switch between throwing error or not
public ActionResult GetUser(string email)
{
    if(Request.IsAjax())
    {
        User user = new User{ name = "Lol", id = "2" };
        if(noError)
            return Json(new { value = user }
        else
            //How do I make this better?
            return Json(new { exception = new { loc = /*this assembly*/"", type = Status.EmailNotFound, email = email});
    }
    //Not really meant for non ajax calls, so no idea what to do here.
    return View();

}

I basically need to create 2 standards, if no error, then it goes in a value object, if error, it uses the exception structure.


How about you create two methods, either on a base controller or as extension methods:

public JsonResult JsonValue(object value)
{
    if (!Request.IsAjax())
        throw new InvalidOperationException("This action is only available to JSON requests");
    return Json(new { value; });
}

public JsonResult JsonError(Exception ex)
{
    if (!Request.IsAjax())
        throw new InvalidOperationException("This action is only available to JSON requests");
    // whatever formatting you need
    return Json(new { exception = new { ex.ToString(); });
}

Then in your action method:

public ActionResult GetUser(string email)
{
    try {
        var user = GetUser();
        return JsonValue(user);
    } catch (Exception ex) {
        return JsonError(ex);
    }
}

You could make your action methods even simpler by defining a custom ActionFilterAttribute that checks for exceptions and sets the JSON error result, then you would only need to put [JsonError] or whatever on your action method, rather than the try/catch block.


What you have there is the easiest way to build JSON results. An alternative would be to use Dictionaries, but those get more verbose.

0

精彩评论

暂无评论...
验证码 换一张
取 消