从另一个访问某个Web API控制器 [英] Access one web api controller from another

查看:229
本文介绍了从另一个访问某个Web API控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个Web API控制器:的PageController BlogController 。它们包含简单的CRUD用于创建网页和博客。每次我创建一个博客,我需要创建一个页面,而不是相反。请告诉我这样做的最好方法是什么?我觉得很奇怪,必须与我的路由发生,如果我从的PageController BlogController 继承。是否有某种方式来调用 CreatePage 的PageController 方法从 BlogController CreateBlog 的方法?我应该干脆辞职自己做两个独立的Ajax调用每次我想创建一个博客?

I have two web api controllers: PageController and BlogController. They contain simple crud for creating pages and blogs. Every time I create a blog, I need to create a page, but not vice versa. Whats the best way of doing this? I feel like something weird must happen with my routing if I inherit from PageController in BlogController. Is there some way to call the CreatePage method in PageController from BlogController's CreateBlog method? Should I simply resign myself to making two separate ajax calls every time I want to create a blog?

推荐答案

如果你将需要有一个需要由多个控制器进行访问,你应该创建一个单独的类来处理通用逻辑在一个集中的一些常见的逻辑方式。

If you are going to need to have some common logic that needs to be accessed by multiple controllers you should create a separate class to handle that common logic in a centralized manner.

本类可以是Web项目,或者在一个单独的项目/组件的一部分。

This class can be part of your web project or in a separate project/assembly.

基本上你正在试图做的是这样的:

Basically what you are trying to do is this:

public class BlogController
{
    public void CreateBlog()
    {
        var pc = new PageController();
        pc.CreatePage();
    }
}
public class PageController
{
    private Database db;
    public void CreatePage()
    {
        var page = new Page();
        db.SavePage(page);
    }
}

和我建议你这样做:

public class BlogController
{
    public void CreateBlog()
    {
        Blog.CreatePage();
    }
}
public class PageController
{
    public void CreatePage()
    {
        Blog.CreatePage();
    }
}
public class Blog
{
    private Database db;
    public static void CreatePage() // does not 
    {
        var page = new Page();
        db.SavePage(page);
    }
}

这篇关于从另一个访问某个Web API控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆