栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > .Net

.net mvc项目 开发API接口

.Net 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

.net mvc项目 开发API接口

开发 1.webApiConfig文件中增加接口访问配置
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
           
            //1.默认路由
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            //2.自定义路由一:匹配到action
            config.Routes.MapHttpRoute(
                name: "ActionApi",
                routeTemplate: "actionapi/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

        }
    }
2.新建控制类,写接口逻辑

       

        [HttpGet]

        [ActionName("getList")]

  public resClass getList(string apiKey, string timeStamp, string status = null )

    {

   //接口逻辑

    }

3.调用

 http://域名/actionapi/{controller}/getList?apiKey=1626666123FD3ED834&timeStamp=1626666123

使用工具调用接口正常,浏览器直接访问显示错误

错误如下:

The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.

原因:写api接口时默认返回的是把你的对象序列化后以XML形式返回,而接口中想返回json列表时会出错解决办法 :在API的webApiConfig文件中加以下代码,清除头文件请求内容

GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();

可选参数设置

定义为null、可选参数需要放在全部必须参数后面

  public resClass getList(string apiKey, string timeStamp, string status = null )

    {

   //接口逻辑

    }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/906662.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号