【吉光片羽】之 Web API

时间:2022-05-26 15:22:42

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});
}