1

私はこれをしたい:

   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();
    }

しかし、IsAjaxRequest と同様に、着信 jsonrequest を検出するためのより良い方法 (および組み込み) がないかどうか疑問に思います。同じURLを使用したいので、「.json」、「.html」などのフォーマット拡張子を扱いたくないことが望ましい.

また、jsonrequest とビューを返す通常の Web リクエストに別の URL を使用したくありません。

4

1 に答える 1

2

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
    }
}
于 2011-02-25T16:07:53.520 に答える