美文网首页
在mvc模式中添加webapi

在mvc模式中添加webapi

作者: wwmin_ | 来源:发表于2017-03-13 13:20 被阅读12次

在App_Start下新建WebApiConfig.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace NFine.Web
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                //注意此处的路由前缀统一添加了'api/',以便和mvc路由区分,如果不修改,则会导致路由路径一样,只会进入同一个路由导致出错
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

在Controllers文件夹下添加webApi路由 TestController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Base;
using System.Net.Http.Headers;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System.IO;

namespace NFine.Web.Controllers
{
    public class testController : ApiController
    {
        [HttpGet]
        public HttpResponseMessage test()
        {
            return "hellow world".HttpResponseSerializeObject(true, "");
        }
}

在Global.asax中注册路由

using NFine.Code;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;

namespace NFine.Web
{
    public class MvcApplication : System.Web.HttpApplication
    {
        /// <summary>
        /// 启动应用程序
        /// </summary>
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            //在此处注册webApi的路由
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }
    }
}

运行程序,然后看能否进入正常网页,并且在浏览器内输入http://localhost:1851/api/test/test,返回{"result":true,"error":"","data":"hellow world"},表示成功!

相关文章

  • 在mvc模式中添加webapi

    在App_Start下新建WebApiConfig.cs 在Controllers文件夹下添加webApi路由 T...

  • WebApi数据检验

    WebAPI的模型校验同ASP.NET MVC的数据校验。 若想在WebAPI加入模型验证,需要三个步骤; 1添加...

  • WebAPI接口调试技巧

    1.了解WebAPI接口 接口模式:基于MVC4.0的WebAPI 承载协议:HTTP 跟踪工具:IE11 请求方...

  • WebApi 2 路由机制

    .net中包含的路由有两种,第一种是MVC模式的按url匹配action,第二种是WebApi模式的按http请求...

  • WebApi—CORS跨域

    添加nuget包:microsoft.aspnet.webapi.cors在WebApiConfig.cs文件中配...

  • MVC,MVVM,CommonJS,AMD,CMD

    MVC和MVVM MVC 模式结构 (Model-View-Control 模型-视图-控制器)在MVC模式中,用...

  • 日常笔记 - MVP

    1 前言 MVP模式是MVC模式在Android上的一种变体,要介绍MVP就得先介绍MVC。在MVC模式中,Act...

  • .NET MVC 兼容不支持 PUT/DELETE 的浏览器

    前端:ASP.NET MVC后端:.NET WebAPI 在系统中,老是有客户抱怨,某某地方修改不了啊、某某记录删...

  • MVP模式

    简介 MVP 是从经典的模式MVC演变而来。 在MVC/MVP模式中Controller/Presenter负责逻...

  • OC新建项目流程

    设置CocoPod,MVC模式 3.添加pch文件 向项目中添加新文件,在Other中选择PCH Filepch....

网友评论

      本文标题:在mvc模式中添加webapi

      本文链接:https://www.haomeiwen.com/subject/jxbfnttx.html