从MVC控制器调用API方法 [英] Call API method from MVC controller

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

问题描述

这是我在API中的方法

that's my method in API

<pre>//   Function to Load Lvl Info
        public HttpResponseMessage getLevelInfo(int GameID,int LvlNO)
        {
            Tbl_FrequancyGames Tbl_FrequancyGames = (from u in (db.Tbl_FrequancyGames) where (u.GameID == GameID && u.LevelNo==LvlNO ) select u).FirstOrDefault();

            
                return Request.CreateResponse(HttpStatusCode.OK, Tbl_FrequancyGames);
            
        }





我的尝试:



如何从MVC控制器中调用它



What I have tried:

How can i call it from MVC Controller

推荐答案

由于此方法返回HTML响应,您实际上无法从另一种MVC方法。好吧,除非你打算使用HTML响应,但这确实没有任何有用的意义。



答案很简单。将此方法拆分为两种方法。一个暴露为API,调用方法来获取数据并将其格式化为HTML响应,另一个方法只是抓取数据并返回它。

Since this method returns an HTML response you really can't call it from another MVC method. Well, unless you're going to use the HTML response but that really doesn't make any useful sense.

The answer to this is very easy. Split this method up into two methods. One exposed as the API that calls the method to get the data and formats it for the HTML response and another method that just grabs the data and returns it.
public HttpResponseMessage getLevelInfo(int GameId, int LvlNO)
{
    var data = GetLevelInfoData(GameId, LvlNO);

    return Request.CreateResponse(HttpStatusCode.OK, data);
}

internal Tbl_FrequancyGames GetLevelInfoData(int GameId, int LevelNo)
{
    Tbl_FrequancyGames Tbl_FrequancyGames = (from u in (db.Tbl_FrequancyGames) where (u.GameID == GameID && u.LevelNo==LevelNo ) select u).FirstOrDefault();

    return Tbl_FrequancyGames;
}


这篇关于从MVC控制器调用API方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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