【吉光片羽】之 Web API
2024-08-25 15:50:59
1.在asp项目中直接添加apiController,需要新增Global.asax文件。再增加一个webapiConfig,如果需要访问方式为"api/{controller}/{action}/{id}“ 修改路由:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Formatting;
using System.Web;
using System.Web.Http;
using System.Web.Security;
using System.Web.SessionState; namespace AS.GroupOn.Web
{
public class Global : System.Web.HttpApplication
{ protected void Application_Start(object sender, EventArgs e)
{
WebApiConfig.Register(GlobalConfiguration.Configuration);
} public override void Init()
{
this.PostAuthenticateRequest += MvcApplication_PostAuthenticateRequest;//用于打开session
base.Init();
} void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
{
System.Web.HttpContext.Current.SetSessionStateBehavior(
SessionStateBehavior.Required);
}
} public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{ config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
); config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer = true;//设定返回方式 // config.Formatters.JsonFormatter.AddQueryStringMapping("$format", "json", "application/json");
//config.Formatters.XmlFormatter.AddQueryStringMapping("$format", "xml", "application/xml");
//config.Formatters.Remove(config.Formatters.JsonFormatter);
//config.Formatters.Remove(config.Formatters.XmlFormatter);
// 取消注释下面的代码行可对具有 IQueryable 或 IQueryable<T> 返回类型的操作启用查询支持。
// 若要避免处理意外查询或恶意查询,请使用 QueryableAttribute 上的验证设置来验证传入查询。
// 有关详细信息,请访问 http://go.microsoft.com/fwlink/?LinkId=279712。
//config.EnableQuerySupport(); // 若要在应用程序中禁用跟踪,请注释掉或删除以下代码行
// 有关详细信息,请参阅: http://www.asp.net/web-api
// config.EnableSystemDiagnosticsTracing();
}
}
}
2.定义HttpResponseMessage 返回类型。
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
private HttpResponseMessage getReturnMessage(int sta, string msg, HttpStatusCode httpStatus = HttpStatusCode.MethodNotAllowed)
{
return Request.CreateResponse(httpStatus, new{status=sta,info=msg});
} private HttpResponseMessage getReturnMessage(int sta,object obj, HttpStatusCode httpStatus = HttpStatusCode.OK)
{
return Request.CreateResponse(httpStatus, new { status = sta, obj});
}
最新文章
- 【转】Win7 64bit Oracle 11g 使用PL/SQL Developer 连接时提示“SQL*Net not properly installed”
- 移动开发发展方向-----Hybird混合开发3大方案
- MVC 4 异步编程简化了
- nginx端口被占用解决方案
- 关于cocostudio加载UI json CCUIHELPER未声明问题
- Struts2+Ajax实现检测用户名是否唯一
- CSS的标签类型
- 动手搭建第一个小程序音视频Demo
- HDU - 2154 线性dp
- vtop工具使用分析
- ZJOI2019一轮停课刷题记录
- Linux内核的冷热缓存
- day13_H5_CSS_1
- 【转】使用Eclipse,将鼠标放在相应方法或字段等元素上时,无法显示提示
- java开发师笔试面试每日12题(1)
- Python爬虫(三)——开封市58同城出租房决策树构建
- SNF快速开发平台MVC-EasyUI3.9之-Session过期处理和页面请求筛选
- php测试for/while/foreach循环速度对比
- Static变量与代码块
- Python - openpyxl 读写操作Excel