结合actionresult和jsonresult

我想做这个:
   public ActionResult Details(int id)
    {
        Object ent = new{ prop1 = 1, prop2 = 2};
        if (Request.AcceptTypes.Contains("application/json"))
         return Json(ent, JsonRequestBehavior.AllowGet);

        ViewData.Model = ent;
        return View();
    }
但是想知道是否有更好的方法(和内置)来检测传入的jsonrequest,类似于IsAjaxRequest。我想使用相同的URL,所以最好不要处理格式扩展,如“.json”,“。html”等。 此外,我不想为jsonrequest和返回视图的普通Web请求提供不同的URL。     
已邀请:
为您的BaseController使用ActionFilterAttribute。并从BaseController继承所有其他控制器
[IsJsonRequest]
public abstract class BaseController : Controller
{
   public bool IsJsonRequest { get; set; }
}

The ActionFilterAttribute
public class IsJsonRequest: ActionFilterAttribute  
{  
    public override void OnActionExecuting(ActionExecutingContext filterContext)  
    { 
        var myController = filterContext.Controller as MyController;
        if (myController != null)
        {

            if (filterContext.HttpContext.Request.AcceptTypes.Contains("application/json"))
            {
                myController.IsJsonRequest = true;
            }
            else
            {
                myController.IsJsonRequest = false;
            }
        }
    }
}

public class TestController : BaseController
{
    public ActionResult Details(int id)
    {
          if (IsJsonRequest)
               return Json Data
          else
               return view
    }
}
    

要回复问题请先登录注册