我正在尝试将自托管OWIN WebApiService从Windows服务应用迁移到WinForms。这是我的Startup.cs代码:
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
// Configure the db context and user manager to use a single instance per request
var oAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/auth/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(31),
//owin providers go here, doesn't matter
};
// Token Generation
app.UseOAuthAuthorizationServer(oAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
app.UseWebApi(ConfigureWebApi());
}
private HttpConfiguration ConfigureWebApi()
{
var config = new HttpConfiguration();
var jsonFormatter = config.Formatters.JsonFormatter;
jsonFormatter.SerializerSettings.Formatting = Formatting.None;
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
jsonFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
config.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
config.Routes.MapHttpRoute(
"DefaultApi",
"api/{controller}/{id}",
new { id = RouteParameter.Optional });
return config;
}
然后,网络服务:
public static class WebService
{
static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public static void Run()
{
log4net.Config.XmlConfigurator.Configure();
var _ip = "localhost";
var _port = "1532";
var url = _ip + ':' + _port;
try
{
WebApp.Start<Startup>(url);
}
catch (Exception ex)
{
log.ErrorFormat("Error on starting web service. Exception : {0}.", ex.Message);
return;
}
log.Info("Service has been started.");
}
}
作为一个Windows服务,它一切顺利,一切正常。但是,当我尝试从Winforms应用程序(从Program.cs或我的表单代码)运行Web服务时 - 它看起来没问题,但我无法通过HTTP客户端(Chrome,Postman等)连接到服务网络,不是通过我的HTTP客户端代码。
是否可以在Winforms中托管Web Api?任何人都可以帮忙吗?
P.S。防火墙已关闭。港口也没关系,我至少试过五次。