سؤال

وبلدي اليوم الثاني مع ASP.NET MVC وأول طلبي لرمز على SO (موافق، وأخذ طريقا مختصرا).

وأنا أبحث عن وسيلة لخلق التصفية التي تعترض الانتاج الحالي من العمل، وبدلا من النواتج JSON (وأنا أعلم من <لأ href = "http://weblogs.asp.net/omarzabir/archive/2008/ 03/10 / إنشاء بقية-API باستخدام-آسيا والمحيط الهادئ، صافي MVC-أن كلا-سلمان-وسهل-xml.aspx-يتحدث "يختلط =" نوفولو noreferrer "> مناهج بديلة ولكن هذا هو لمساعدتي في فهم مرشحات). أريد أن تجاهل أي آراء المرتبطة العمل ومجرد الاستيلاء على ViewData [ "إخراج"]، وتحويله إلى JSON وإرساله للعميل. الفراغات لملء:

وTestController.cs:

[JSON]
public ActionResult Index()
{
    ViewData["Output"] = "This is my output";
    return View();
}

وJSONFilter.cs:

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
   /*
    * 1. How to override the View template and set it to null?
    * ViewResult { ViewName = "" } does not skip the view (/Test/Index)
    * 
    * 2. Get existing ViewData, convert to JSON and return with appropriate
    * custom headers
    */
}

تحديث: أدت إجابات المجتمعية لتحقيق أكثر ل<لأ href = "http://aleembawany.com/2009/03/27/aspnet-mvc-create-easy-rest-api-with-json-and -xml / "يختلط =" نوفولو noreferrer "> تصفية JSON / POX .

هل كانت مفيدة؟

المحلول

وأود أن أقترح أن ما كنت حقا تريد القيام به هو استخدام نموذج بدلا من عناصر ViewData التعسفية وتجاوز OnActionExecuted بدلا من OnActionExecuting. وبهذه الطريقة يمكنك ببساطة استبدال النتيجة مع JsonResult الخاص بك قبل ان يحصل على تنفيذه، وبالتالي المقدمة للمتصفح.

public class JSONAttribute : ActionFilterAttribute
{
   ...

    public override void OnActionExecuted( ActionExecutedContext filterContext)
    {
        var result = new JsonResult();
        result.Data = ((ViewResult)filterContext.Result).Model;
        filterContext.Result = result;
    }

    ...
}

[JSON]public ActionResult Index()
{
    ViewData.Model = "This is my output";
    return View();
}

نصائح أخرى

وأنت لم تذكر إلا إعادة JSON مشروط، لذلك إذا كنت ترغب في العمل للعودة JSON في كل مرة، لماذا لا تستخدم:

public JsonResult Index()
{
    var model = new{ foo = "bar" };
    return Json(model);
}

وربما هذا <وأ href = "https://stackoverflow.com/questions/320291/how-to-post-an-array-of-complex-objects-with-json-jquery-to-asp-net- MVC-سيطروا على "> آخر يمكن أن تساعدك على الطريق الصحيح. وظيفة أعلاه هو أيضا وسيلة

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top