OWIN Self-Host + Web Api 连接无法通过 Postman 发出请求
OWIN Self-Host + Web Api connection cant make requests through Postman
我正在尝试自行托管 Web API。当我通过我的程序调用请求时它工作正常,API 控制器在哪里。但我无法通过 Postman Client 提出请求。可能是什么问题?
Api 控制器
public class MyApiController : ApiController
{
public string Get()
{
return "Get";
}
}
Startup.cs
public class Startup
{
public void Configuration(IAppBuilder appBuilder)
{
var config = new HttpConfiguration();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
appBuilder.UseWebApi(config);
}
}
Program.cs
class Program
{
static void Main(string[] args)
{
string url = "http://localhost:44300/";
using (WebApp.Start<Startup>(url))
{
var client = new HttpClient();
var response = client.GetAsync(url + "api/myapi").Result;
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
}
Console.ReadLine();
}
}
看来您的问题出在您的 main 方法中。在C#中,using
语句(link)创建资源,执行块中的代码,然后释放资源。
在您发布的示例中,您的 WebApp 在将响应打印到控制台后立即处理(并且在您能够使用浏览器发出请求之前)。
这些编辑应该允许您保留 WebApp in-scope 以便使用该框架。
class Program
{
static void Main(string[] args)
{
string url = "http://localhost:44300/";
using (WebApp.Start<Startup>(url))
{
var client = new HttpClient();
var response = client.GetAsync(url + "api/myapi").Result;
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
Console.WriteLine("WebApp Ready");
Console.ReadLine();
}
Console.WriteLine("WebApp disposed.");
Console.ReadLine();
}
}
我正在尝试自行托管 Web API。当我通过我的程序调用请求时它工作正常,API 控制器在哪里。但我无法通过 Postman Client 提出请求。可能是什么问题?
Api 控制器
public class MyApiController : ApiController
{
public string Get()
{
return "Get";
}
}
Startup.cs
public class Startup
{
public void Configuration(IAppBuilder appBuilder)
{
var config = new HttpConfiguration();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
appBuilder.UseWebApi(config);
}
}
Program.cs
class Program
{
static void Main(string[] args)
{
string url = "http://localhost:44300/";
using (WebApp.Start<Startup>(url))
{
var client = new HttpClient();
var response = client.GetAsync(url + "api/myapi").Result;
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
}
Console.ReadLine();
}
}
看来您的问题出在您的 main 方法中。在C#中,using
语句(link)创建资源,执行块中的代码,然后释放资源。
在您发布的示例中,您的 WebApp 在将响应打印到控制台后立即处理(并且在您能够使用浏览器发出请求之前)。
这些编辑应该允许您保留 WebApp in-scope 以便使用该框架。
class Program
{
static void Main(string[] args)
{
string url = "http://localhost:44300/";
using (WebApp.Start<Startup>(url))
{
var client = new HttpClient();
var response = client.GetAsync(url + "api/myapi").Result;
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
Console.WriteLine("WebApp Ready");
Console.ReadLine();
}
Console.WriteLine("WebApp disposed.");
Console.ReadLine();
}
}