之前发过一篇随笔,说的WCF配置文件配置问题。里面也配了跨域支持,但是jsoncollback只支持Get请求,Post请求是解决不了,所以这里把真正的WCF跨域问题贴出来。
话不多说,直接帖配置文件。
1 <system.webServer> 2 <httpProtocol> 3 <customHeaders> 4 <add name="Access-Control-Allow-Origin" value="*" /> 5 <add name="Access-Control-Allow-Headers" value="Content-Type" /> 6 <add name="Access-Control-Allow-Methods" value="GET, POST,PUT, DELETE, OPTIONS" /> 7 </customHeaders> 8 </httpProtocol> 9 <modules runAllManagedModulesForAllRequests="true" /> 10 <!-- 11 若要在调试过程中浏览 Web 应用程序根目录,请将下面的值设置为 True。 12 在部署之前将该值设置为 False 可避免泄露 Web 应用程序文件夹信息。 13 --> 14 <directoryBrowse enabled="true" /> 15 <!--<handlers> 16 --> 17 <!--移除 IIS下的OPTIONSVerbHandler Handle Mapping 解决跨域问题--> 18 <!-- 19 <remove name="OPTIONSVerbHandler" /> 20 </handlers>--> 21 </system.webServer>
Http进行Post请求时得先发送一次OPTIONS请求,与服务器进行跨域验证请求,服务器验证通过后才会发送需要发送的Post请求完成整个接口请求过程。
因此这里必须先处理客户端发送的OPTIONS请求。
除了上面的配置文件外,还需在Global里面加上处理请求的方法。代码这里
1 /// <summary> 2 /// 移动跨域请求,会请求两次,第一次OPTIONS 空数据请求,为了获取是否允许跨域,第二次才是带数据请求,所以为了避免程序上一些Bug,空请求时就直接返回,不需要经过业务处理. 3 /// </summary> 4 /// <param name="sender"></param> 5 /// <param name="e"></param> 6 protected void Application_BeginRequest(object sender, EventArgs e) 7 { 8 if (HttpContext.Current.Request.HttpMethod == "OPTIONS") 9 { 10 Response.End(); 11 } 12 }
--------------------------------------------------------------不华丽的分割线--------------------------------------------
这里顺带说一下如果接口需要进行大文件传输,需要把传输管道容量开到最大的话这样配置,这里的配置是最大容量配置:
1 <bindings> 2 <webHttpBinding> 3 <binding name="ServiceProxyBinding" closeTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:30:00" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647"> 4 <readerQuotas maxStringContentLength="2147483647" /> 5 </binding> 6 </webHttpBinding> 7 </bindings>
--------------------------------------------------------------不华丽的分割线--------------------------------------------
既然要多点东西的话把这个也留着吧:
<runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly> <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-10.0.0.0" newVersion="10.0.0.0" /> </dependentAssembly> </assemblyBinding> </runtime>
解决引用的包及项目版本包不匹配或者过低问题。
--------------------------------------------------------------不华丽的分割线--------------------------------------------
既然都说了那么多,那干脆把Log4也记在这里吧。
<configSections>
<!-- 添加log4net 的配置 -->
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
</configSections>
<!--实现log4net start--> <log4net> <!--错误日志--> <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender"> <file value="Log\\LogError\\" /> <appendToFile value="true" /> <rollingStyle value="Date" /> <datePattern value="yyyy\\yyyyMM\\yyyyMMdd'.txt'" /> <staticLogFileName value="false" /> <param name="MaxSizeRollBackups" value="100" /> <layout type="log4net.Layout.PatternLayout"> <!--每条日志末尾的文字说明--> <!--输出格式--> <!--样例:2008-03-26 13:42:32,111 [10] INFO Log4NetDemo.MainClass [(null)] - info--> <conversionPattern value="%newline %n记录时间:%date %n线程ID:[%thread] %n日志级别: %-5level %n错误描述:%message%newline %n" /> </layout> </appender> <!--Info日志--> <appender name="InfoAppender" type="log4net.Appender.RollingFileAppender"> <param name="File" value="Log\\LogInfo\\" /> <param name="AppendToFile" value="true" /> <param name="MaxFileSize" value="10240" /> <param name="MaxSizeRollBackups" value="100" /> <param name="StaticLogFileName" value="false" /> <param name="DatePattern" value="yyyy\\yyyyMM\\yyyyMMdd'.txt'" /> <param name="RollingStyle" value="Date" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%newline %n记录时间:%date %n线程ID:[%thread] %n日志级别: %-5level %n日志描述:%message%newline %n" /> </layout> </appender> <!--监控日志--> <appender name="MonitorAppender" type="log4net.Appender.RollingFileAppender"> <param name="File" value="Log\\LogMonitor\\" /> <param name="AppendToFile" value="true" /> <param name="MaxFileSize" value="10240" /> <param name="MaxSizeRollBackups" value="100" /> <param name="StaticLogFileName" value="false" /> <param name="DatePattern" value="yyyy\\yyyyMM\\yyyyMMdd'.txt'" /> <param name="RollingStyle" value="Date" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%newline %n记录时间:%date %n线程ID:[%thread] %n日志级别: %-5level %n跟踪描述:%message%newline %n" /> </layout> </appender> <!--Error日志--> <logger name="LogError"> <level value="ERROR" /> <appender-ref ref="RollingLogFileAppender" /> </logger> <!--Info日志--> <logger name="LogInfo"> <level value="INFO" /> <appender-ref ref="InfoAppender" /> </logger> <!--监控日志--> <logger name="LogMonitor"> <level value="Monitor" /> <appender-ref ref="MonitorAppender" /> </logger> </log4net> <!--log4net end-->
一天一个日志文件,文件路径在项目的Log下面,有LogError和LogInfo两个文件夹存放不同的日志文件。
具体的LogHelp在这里:
using System; using System.Collections.Generic; using System.Data.Entity.Validation; using System.Linq; using System.Text; [assembly: log4net.Config.XmlConfigurator(Watch = true)] namespace Test.Base { public class LoggerHelper { private static readonly log4net.ILog LogInfo = log4net.LogManager.GetLogger("LogInfo"); private static readonly log4net.ILog LogError = log4net.LogManager.GetLogger("LogError"); private static readonly log4net.ILog LogMonitor = log4net.LogManager.GetLogger("LogMonitor"); /// <summary> /// 记录Error日志 /// </summary> /// <param name="errorMsg"></param> /// <param name="ex"></param> public static void Error(string errorMsg, Exception ex = null) { if (ex != null) { if (ex.InnerException != null) { LogError.Error(errorMsg, ex.InnerException); } else { LogError.Error(errorMsg, ex); } } else { LogError.Error(errorMsg); } } /// <summary> /// 记录Info日志 /// </summary> /// <param name="msg"></param> /// <param name="ex"></param> public static void Info(string msg, Exception ex = null) { if (ex != null) { LogInfo.Info(msg, ex); } else { LogInfo.Info(msg); } } /// <summary> /// 记录Monitor日志 /// </summary> /// <param name="msg"></param> public static void Monitor(string msg) { LogMonitor.Info(msg); } } }
要怎么改,怎么写,自己改嘛。
--------------------------------------------------------------不华丽的分割线--------------------------------------------
这里记录一位同事传授的在线api方法,感谢老哥,给予了太多帮助。
protected void Application_Start(object sender, EventArgs e) { SwaggerWCFInit(); RouteTable.Routes.Add(new ServiceRoute("Service", new WebServiceHostFactory(), typeof(Service))); RouteTable.Routes.Add(new ServiceRoute("api", new WebServiceHostFactory(), typeof(SwaggerWcfEndpoint))); //HibernatingRhinos.Profiler.Appender.EntityFramework.EntityFrameworkProfiler.Initialize(); } protected void SwaggerWCFInit() { InfoContact infoContact = new InfoContact { Name = "名字", Email = "邮箱", Url = "地址" }; InfoLicense infoLicense = new InfoLicense { Name = "", Url = "" }; Info info = new Info { Title = "SampleService(备注信息)", Description = "Sample Service to test SwaggerWCF", Contact = infoContact, License = infoLicense, TermsOfService = "Terms of Service", Version = "1.0.0", }; //var security = new SecurityDefinitions //{ // { // "api-gateway", new SecurityAuthorization // { // Type = "oauth2", // Name = "api-gateway", // Description = "Forces authentication with credentials via an api gateway", // Flow = "password", // Scopes = new Dictionary<string, string> // { // { "author", "use author scope"}, // { "admin", "use admin scope"}, // }, // AuthorizationUrl = "http://yourapi.net/oauth/token" // } // } //}; SwaggerWcfEndpoint.Configure(info); }
嗯~~~,翻了一下,东西还是挺多的,打算重写一个吧,好好收集一下。
还有一些其它的帮助类都在这里:http://www.cnblogs.com/AV1973/p/8675257.html,希望能帮助到更多的人吧,程序员,都辛苦。
-----------------------~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~--------------------留笔。