我有一个C#dll来使用Entity Framework查询数据。之后,我使用owin创建一个rest api来引用dll来获取数据。我有两个示例:一个是使用控制台应用程序来访问数据,它没问题。另一个是我将其余的api放在Windows服务中,然后访问它。它返回空。我不知道为什么。
C#dll:
答案 0 :(得分:0)
ef dll:
public class DemoContext:DbContext
{
private static DemoContext _instance;
public DemoContext() : base("MyDemoConnection")
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<DemoContext, Configuration>());
}
public static DemoContext Instance
{
get
{
if (_instance == null)
{
_instance = new DemoContext();
}
return _instance;
}
}
public DbSet<Student> Students { get; set; }
public DbSet<Teacher> Teachers { get; set; }
}
owin api:
public class Startup
{
public void Configuration(IAppBuilder appBuilder)
{
// Configure Web API for self-host.
HttpConfiguration config = new HttpConfiguration();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
appBuilder.UseWebApi(config);
}
}
public class TeachersController : ApiController
{
[HttpGet]
[Route("api/teachers")]
public HttpResponseMessage Get()
{
try
{
var _context = DemoContext.Instance;
var teachers = _context.Teachers.ToList();
var response = Request.CreateResponse(HttpStatusCode.OK, teachers);
return response;
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.OK, ex.Message);
}
}
}
控制台应用:
class Program
{
static void Main(string[] args)
{
string baseAddress = "http://localhost:9000/";
// Start OWIN host
using (WebApp.Start<Startup>(url: baseAddress))
{
// Create HttpCient and make a request to api/values
/* HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.GetAsync(baseAddress + "api/values").Result;
var result = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(result);*/
Console.ReadLine();
}
}
}
windowservice:
public partial class HostOwin : ServiceBase
{
private IDisposable owin;
public HostOwin()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
string baseAddress = "http://localhost:9000/";
owin = WebApp.Start<Startup>(url: baseAddress);
}
protected override void OnStop()
{
owin.Dispose();
}
}