C# ASP.NET WebAPI模板的使用
我不确定这是否是一个应该就此提出的问题,但我想不出更好的问题。我想知道的是:有没有人真正使用VisualStudio附带的WebAPI4.5.2模板。我写C#Web应用程序已经有一段时间了,我觉得这些模板太过臃肿,难以处理。它们似乎也让开发人员无法理解实际情况下是如何工作的。你同意还是不同意,如果我想称自己为.Net Web开发人员,我应该使用这些模板吗C# ASP.NET WebAPI模板的使用,c#,asp.net,asp.net-web-api,C#,Asp.net,Asp.net Web Api,我不确定这是否是一个应该就此提出的问题,但我想不出更好的问题。我想知道的是:有没有人真正使用VisualStudio附带的WebAPI4.5.2模板。我写C#Web应用程序已经有一段时间了,我觉得这些模板太过臃肿,难以处理。它们似乎也让开发人员无法理解实际情况下是如何工作的。你同意还是不同意,如果我想称自己为.Net Web开发人员,我应该使用这些模板吗 这当然是非常固执己见的,但我同意;默认的(与MVC相关的)模板充斥着不必要的特性,它们没有任何精巧和意义。我已经使用自定义模板很长时间了,只是
这当然是非常固执己见的,但我同意;默认的(与MVC相关的)模板充斥着不必要的特性,它们没有任何精巧和意义。我已经使用自定义模板很长时间了,只是为了避开这个(令人沮丧的)问题 请注意,Visual Studio现在可以选择创建一个空网站,并允许您选择只包含WebAPI,而不强制您包含ASP.NET MVC。这产生了一个很好的小项目 如果您确实在WebAPI上做了很多实验,并且不想让您的硬盘成为充满VisualStudio项目的集群炸弹,我可以强烈推荐LinqPad。只需一点点代码,您就可以创建一个自托管进程并将其用作模板。例如:
#define NONEST
void Main()
{
string baseAddress = "http://localhost:9000/";
try
{
// Start OWIN host
using (WebApp.Start<Startup>(url: baseAddress))
{
// Create HttpCient and make a request to api/values
HttpClient client = new HttpClient();
var response = client.GetAsync(baseAddress + "api/values").Result;
Console.WriteLine("response: " + response);
Console.WriteLine("result: " + response.Content.ReadAsStringAsync().Result);
}
}
finally
{
// LinqPad keeps the AppDomain running to reduce compile time.
// Force app domain unload (Displays "Query ended unexpectedly")
// You can also press shift-F5 to unload the AppDomain.
AppDomain.Unload(AppDomain.CurrentDomain);
}
}
// Define other methods and classes here
public class Startup
{
// This code configures Web API. The Startup class is specified as a type
// parameter in the WebApp.Start method.
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 ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
#定义非测试
void Main()
{
字符串基地址=”http://localhost:9000/";
尝试
{
//在主机中启动OWIN
使用(WebApp.Start(url:baseAddress))
{
//创建HttpCient并向api/values发出请求
HttpClient=新的HttpClient();
var response=client.GetAsync(baseAddress+“api/values”).Result;
Console.WriteLine(“响应:+response”);
Console.WriteLine(“结果:+response.Content.ReadAsStringAsync().result”);
}
}
最后
{
//LinqPad保持AppDomain运行以减少编译时间。
//强制卸载应用程序域(显示“查询意外结束”)
//也可以按shift-F5卸载AppDomain。
AppDomain.Unload(AppDomain.CurrentDomain);
}
}
//在此处定义其他方法和类
公营创业
{
//此代码配置Web API。启动类被指定为类型
//WebApp.Start方法中的参数。
公共无效配置(IAppBuilder appBuilder)
{
//为自主机配置Web API。
HttpConfiguration config=新的HttpConfiguration();
config.Routes.MapHttpRoute(
名称:“DefaultApi”,
routeTemplate:“api/{controller}/{id}”,
默认值:新建{id=RouteParameter.Optional}
);
appBuilder.UseWebApi(配置);
}
}
公共类值控制器:ApiController
{
//获取api/值
公共IEnumerable Get()
{
返回新字符串[]{“value1”,“value2”};
}
}