【问题标题】:Calling API Controller from MVC View从 MVC 视图调用 API 控制器
【发布时间】:2016-01-13 19:56:24
【问题描述】:

您好,我已经开始学习 Web API 我目前有一个 Web Api 控制器,位于我的项目的根目录(不在文件夹中),如下所示

  public class LearnWebApi : ApiController
  {
    // GET api/<controller>
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/<controller>/5
    public string Get(int id)
    {
        return "value";
    }

    // POST api/<controller>
    public void Post([FromBody]string value)
    {
    }

    // PUT api/<controller>/5
    public void Put(int id, [FromBody]string value)
    {
    }

    // DELETE api/<controller>/5
    public void Delete(int id)
    {
    }
  }

现在我有一个家庭控制器,它位于控制器文件夹中,视图位于视图文件夹中。现在在视图上我有一个按钮,当我单击此按钮时,我想调用 Api Web Controller Get Method 并传入 ID 2 例如我在以下位置放置了一个断点

// GET api/<controller>/5
public string Get(int id)
{
    return "value";
}

但它没有被击中,而是我在浏览器中收到消息说

404 Not Found - http://localhost:27774/~/api/LearnWebApi/Get/5"

我的 jquery 在这里

<h2>Index</h2>
<button id="PressMe">Press me</button>

<script type="text/javascript">
$(document).ready(function () {

    $('#PressMe').click(function () {
        $.ajax({
            type: "POST",
            dataType: "json",
            // data: source,
            url: '~/api/LearnWebApi/Get/5', // url of Api controller not mvc
            success: function (data) {
                alert("Redirect true !");

            },
            error: function () {
                alert('erere');
            }

        });

        return false;

    });

});
</script>

这是我的 WebApiConfig

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

以下是我的项目是如何构建的

现在我想这可能与我指定的 URL 有关,但我不确定是否有任何帮助?

【问题讨论】:

    标签: jquery asp.net-mvc asp.net-web-api


    【解决方案1】:

    我没有你的确切项目结构,但我有一个完美的工作 api 演示,这是我今天创建的。

    很抱歉,我无法上传屏幕截图,因为我刚刚开始使用 stackoverflow,而且我还是初学者,他们还不允许我上传屏幕截图。

    但我希望这会有所帮助。

    控制器名称是控制器文件夹下的 Default1。这是代码。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Web.Http;
    using demowebapi1.Models;
    
    namespace demowebapi1.Controllers
    {
       public class Default1Controller : ApiController
    {
        public void test1(List<Class1> obj)
        {
           for(int i=0; i<obj.Count;i++)
           {
               string s1 = obj[i].text1;
               string s2 = obj[i].text2;
    
           }
         }
      }
    }
    

    我在控制器中使用了一个列表对象作为我的操作方法的参数。 Class1 是我的模型类,位于模型文件夹下。 这是代码。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace demowebapi1.Models
    {
      public class Class1
      {
        public string text1 { get; set;}
        public string text2 {get; set;}
      } 
     }
    

    这是我的 webapiconfig.cs 代码,位于 app_start 文件夹中。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web.Http;
    
    namespace demowebapi1
    {
      public static class WebApiConfig
     {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
    
            // Web API routes
            config.MapHttpAttributeRoutes();
    
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
          }
          }
      }
    

    这是一个名为“test1.html”的 html 文件,我通过它进行 jquery ajax 调用。请注意,我使用的是 post 而不是 get。

    <html>
    <head>
    <title> </title>
    <script src="jquery-2.1.3.js"></script> 
     </head>
     <body>
      <input type="text" id="txt0" />  <input type="text" id="text0" class="tmp" />  <br />
       <input type="text" id="txt1" />  <input type="text" id="text1" class="tmp" />
    
       <input type="button" onclick="makepost();" value="click me" /> 
       <script type="text/javascript">
    
        function makepost()
        {
        var POExpedite = [];
        var arr = $(".tmp");
    
        console.log(arr.length);
    
    
    
        for(var i=0;i<arr.length; i++)
        {
            var str1 = $("#txt" + i).val();           
    
            alert(str1);
    
            var str2 = $("#text" + i).val();
    
            alert(str2);
    
    
    
            POExpedite.push({
    
                "text1": str1,
                "text2": str2
    
            });
    
        }
    
        console.log(JSON.stringify(POExpedite));
    
        var apiurl = "http://localhost:4086/api/Default1/test1"
    
        $.ajax({
            type: "POST",
            contentType: "application/json",
            url: apiurl,
            data: JSON.stringify(POExpedite),
            async: false
          });
       }
      </script>
      </body>
      </html>
    

    【讨论】:

    • 太好了,按照您所做的并更改了端口号并且它起作用了,我只能假设当我将 mvc 控制器与 api 控制器混合时,Visual Studio 有点困惑!我将不得不研究使用 api 控制器处理 mvc 控制器的最佳方法是什么,因为我知道以后我将在我的项目中使用它们,所以最好现在投入时间并获得理解,我认为这可能与配置有关,可能需要调整,但当我遇到它时,我会越过那座桥。感谢您的帮助,我已将其标记为答案:)
    • 很高兴它为您解决了 :) 并感谢您将其标记为答案。
    【解决方案2】:

    请注意,您需要先运行您的 web api 项目,并且它应该保持运行。 只有这样你才能进行 ajax 调用。

    在我的例子中,web api 控制器和 test1.html 文件在同一个项目中。

    如果你的 web api 项目不同,而你的 mvc 项目不同,那么你很可能会遇到跨站点脚本错误。

    更多信息可以在下面的链接中找到。

    http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

    【讨论】:

    • 我知道,这就是我这样做的原因,但在聊天讨论后我们发现找不到 web api 控制器
    • 首先在你的 jqeury ajax 调用中修改 url 字符串并使用 contenttype 而不是 datatype。我不确定数据类型是否有效。我从未使用过它,但内容类型对我有用,这就是为什么建议您使用它。 url: "localhost:port number/api/Controller/action/action 参数(如果需要) contentType: "application/json"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-27
    • 1970-01-01
    相关资源
    最近更新 更多