Access one web api controller from another

2019-07-06 17:54发布

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?

2条回答
再贱就再见
2楼-- · 2019-07-06 18:30

Try to create object of the controller and then use the respective functions.

查看更多
相关推荐>>
3楼-- · 2019-07-06 18:40

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.

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

And I am suggesting that you do this:

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);
    }
}
查看更多
登录 后发表回答