简体   繁体   English

ASP.NET MVC4 Controller方法在C#中返回具体类型而不是JSON

[英]ASP.NET MVC4 Controller methods return concrete types instead of JSON in C#

How can I make a controller method return a list of objects and do something to it before sending the result back to the browser? 在将结果发送回浏览器之前,如何让控制器方法返回对象列表并对其执行某些操作?

Changing the return type of a controller method from JsonResult to List will return the type of the result "System.Collections.Generic.List`1[MyObject]" in the request. 将控制器方法的返回类型从JsonResult更改为List将返回请求中结果“System.Collections.Generic.List`1 [MyObject]”的类型。

I am trying to do it through a custom result filter but when the result gets to the filter OnResultExecuted method, it is already jsonified to the text above. 我试图通过自定义结果过滤器,但当结果到达过滤器OnResultExecuted方法时,它已被jsonified到上面的文本。 Is there anything I can do in the OnResultExecuting method to retrieve the list returned from the method and modify it? 我可以在OnResultExecuting方法中检索从方法返回的列表并修改它吗?

Thanks! 谢谢!

If I understand from the comments, I think you are looking to do something like this 如果我从评论中理解,我认为你正在寻找这样的事情

public interface ICtrlService {
    List<MyObject> SomeMethod();
}


public ControllerA : Controller {
    ICtrlService service;

    public MyController(ICtrlService service){
        this.service = service
    }

    public JsonResult SomeAction() {
        List<MyObject> result = service.SomeMethod();
        return Json(result);
    }
}

Your proxy can implement the service as stated. 您的代理可以按照规定实施服务。

public class ProxyB : ICtrlService {

    public List<MyObject> SomeMethod() {...}

}

You could even use the proxy as the injected dependency to your controller making sure that the controller will actually be providing the needed functionality. 您甚至可以使用代理作为控制器的注入依赖项,确保控制器实际上将提供所需的功能。

Or use the common service as a dependency for your proxy. 或者使用公共服务作为代理的依赖项。

public class ProxyB {
    ICtrlService service;
    public ProxyB(ICtrlService service) {
        this.service = service;
    }

    public List<MyObject> SomeProxyMethod() {
        var result = service.SomeMethod();    
        //...Do what you want with object
        return result;
    }
}

This will save the proxy from having to make calls to the controller as it will have access to the same common service functionality. 这将使代理不必调用控制器,因为它可以访问相同的公共服务功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM