c# mvc 中webservice 和 webapi 共存
程序员文章站
2022-07-08 16:44:21
...
webapi 创建
1.先创建一个mvc项目,注册webapi
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using System.Net.Http.Formatting;
using Newtonsoft.Json.Serialization;
using System.Web.Http.Cors;
namespace API
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
//跨域配置
config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
config.Filters.Add(new MerchantErrorHandleAttribute("错误处理"));
// Web API 配置和服务
var jsonFormatter = new JsonMediaTypeFormatter();
//optional: set serializer settings here
config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));
// Web API 路由
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
2.相对应的类和代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web;
namespace API
{
public class JsonContentNegotiator: IContentNegotiator
{
private readonly JsonMediaTypeFormatter _jsonFormatter;
public JsonContentNegotiator(JsonMediaTypeFormatter formatter)
{
_jsonFormatter = formatter;
}
public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
{
var result = new ContentNegotiationResult(_jsonFormatter, new MediaTypeHeaderValue("application/json"));
return result;
}
}
}
using Newtonsoft.Json;
using RET.Model.merchant;
using RET_API.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Text;
using System.Web;
using System.Web.Http.Filters;
namespace API
{
public class MerchantErrorHandleAttribute : System.Web.Http.Filters.ExceptionFilterAttribute
{
private string _msg = string.Empty;
public MerchantErrorHandleAttribute() { }
public MerchantErrorHandleAttribute(string msg)
{
this._msg = msg;
}
public override void OnException(System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext)
{
base.OnException(actionExecutedContext);
var request = HttpContext.Current.Request;
var logDetail = new
{
//获取action名称
ActionName = actionExecutedContext.ActionContext.ActionDescriptor.ActionName,
//获取Controller 名称
ControllerName = actionExecutedContext.ActionContext.ActionDescriptor.ControllerDescriptor.ControllerName,
Navigator = request.UserAgent,
//获取访问的ip
IP = request.UserHostAddress,
UserHostName = request.UserHostName,
UrlReferrer = request.UrlReferrer != null ? request.UrlReferrer.AbsoluteUri : "",
Browser = request.Browser.Browser + " - " + request.Browser.Version + " - " + request.Browser.Type,
//获取request提交的参数
Paramaters = GetRequestValues(actionExecutedContext),
//获取response响应的结果
//ExecuteResult = GetResponseValues(actionExecutedContext), //这句会报错,异常没有处理结果
AttrTitle = this._msg,
ErrorMsg = string.Format("错误信息:{0}, 异常跟踪:{1}", actionExecutedContext.Exception.Message, actionExecutedContext.Exception.StackTrace),
RequestUri = request.Url.AbsoluteUri
};
// 写log
LogInfo.WriteLogInfo("MerchantErrorHandleAttribute", "MerchantError", JsonConvert.SerializeObject(logDetail));
actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(System.Net.HttpStatusCode.InternalServerError, actionExecutedContext.Exception.Message);
}
/// <summary>
/// 读取request 的提交内容
/// </summary>
/// <param name="actionExecutedContext"></param>
/// <returns></returns>
public string GetRequestValues(HttpActionExecutedContext actionExecutedContext)
{
Stream stream = actionExecutedContext.Request.Content.ReadAsStreamAsync().Result;
Encoding encoding = Encoding.UTF8;
/*
这个StreamReader不能关闭,也不能dispose, 关了就傻逼了
因为你关掉后,后面的管道 或拦截器就没办法读取了
*/
var reader = new StreamReader(stream, encoding);
string result = reader.ReadToEnd();
/*
这里也要注意: stream.Position = 0;
当你读取完之后必须把stream的位置设为开始
因为request和response读取完以后Position到最后一个位置,交给下一个方法处理的时候就会读不到内容了。
*/
stream.Position = 0;
return result;
}
}
}
3.RouteConfig中配置,过滤asmx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace API
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{*x}", new { x = @".*\.asmx(/.*)?" });
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
4.Global中注册api
using GA.Web.Framework.Logs;
using GA.Web.Framework.Nhibernate;
using GA.Web.Framework.Unit;
using ImageMagick;
using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace RET_API
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
//配置API
GlobalConfiguration.Configure(WebApiConfig.Register);
//获取依赖注入配置文件
//string strFile = HttpContext.Current.Server.MapPath("~/Unity.config");
//根据配置文件获取依赖注入容器
//IUnityContainer container = ContainerFactory.getContainer(strFile);
//存储容器
//UnitContainer.Container = container;
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
//initSessionBuilder();
//MagickNET.SetGhostscriptDirectory(@"" + ConfigurationManager.AppSettings["PdfToImage"]);
//初始化日志组件
//LogsHelper.InitLogs("BS");
}
/// <summary>
/// 注册数据库Session存储模式
/// </summary>
//private void initSessionBuilder()
//{
//创建NHibernate Session实例
//SessionBuilder.sessionStorage = new HttpSessionStorage();
//}
}
}
上一篇: spring mvc中的几类拦截器对比
下一篇: jsp+servlet实现登陆注册