zoukankan      html  css  js  c++  java
  • MVC5项目中添加Wep API

    一、查看MVC版本,决定你有没有必要看这篇文章 
    打开web.config,看到以下内容

          <dependentAssembly>
            <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
          </dependentAssembly>

    二、添加Controller 
    Controller文件夹 右击-添加-Web API控制器(v2.1),建好后,系统自动创建以下文件: 
    App_Start/WebApiConfig.cs(没有请添加)

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

    三、修改Global.asax.cs 
    打开Global.asax.cs,添加:GlobalConfiguration.Configure(WebApiConfig.Register);

    完整代码如下

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Optimization;
    using System.Web.Routing;
    using System.Web.Http;
    
    namespace FirstMvc5
    {
        public class MvcApplication : System.Web.HttpApplication
        {
            protected void Application_Start()
            {
                AreaRegistration.RegisterAllAreas();
                GlobalConfiguration.Configure(WebApiConfig.Register);
                FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
                RouteConfig.RegisterRoutes(RouteTable.Routes);
                BundleConfig.RegisterBundles(BundleTable.Bundles);
            }
        }
    }
    

    四、添加 WebAPI Help 
    (本部分内容来源微软官方:http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/creating-api-help-pages) 
    工具菜单中,选择NuGet包管理器,然后选择程序包管理器控制台。在程序包管理器控制台窗口中,键入下列命令之一 ︰

    C#应用程序 ︰Install-Package Microsoft.AspNet.WebApi.HelpPage 
    Visual Basic应用程序 ︰Install-Package Microsoft.AspNet.WebApi.HelpPage.VB

    自动添加了Areas文件夹

    五、大功告成 
    生成,预览http://xxx:8089/Help

    其实更简单的就是创建项目的时候同时选择MVC和WebAPI,以上只是我的补救措施

  • 相关阅读:
    Oracle 启动关闭
    GridView 自动序号
    提高数据库处理查询速度
    Linux目录结构
    GridView 全选
    Linux 窗口启动和命令行启动设置
    Oracle 备份
    二进制部署K8S集群(三)前置准备工作之准备签发证书环境
    nginx的location详解
    二进制部署K8S集群(七)Master节点之kubeapiserver集群部署
  • 原文地址:https://www.cnblogs.com/jf-guo/p/6216833.html
Copyright © 2011-2022 走看看