csharp Nancy和ASP.NET Web API比较
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp Nancy和ASP.NET Web API比较相关的知识,希望对你有一定的参考价值。
namespace nancyapi
{
public class ApiModule : Nancy.NancyModule
{
private ITaskRepository taskRepository;
public ApiModule() {
taskRepository = new TaskRepository();
Get["/api"] = x => taskRepository.All;
Get["/api/{id}"] = x => taskRepository.Find(x.id);
Post["/api"] = pars =>
{
var task = new Task();
task.Description = Request.Form.description;
task.Priority = Request.Form.priority;
task.CreatedOn = Request.Form.createdon;
var id = taskRepository.InsertOrUpdate(task);
taskRepository.Save();
return JsonEncode(id);
};
Put["/api/{id}"] = pars =>
{
var task = new Task();
task.Id = pars.id;
task.Description = Request.Form.description;
task.Priority = Request.Form.priority;
task.CreatedOn = Request.Form.createdon;
var id = taskRepository.InsertOrUpdate(task);
taskRepository.Save();
return JsonEncode(id);
};
Delete["/api/{id}"] = x => taskRepository.Delete(x.id);
}
}
}
namespace aspapi.Controllers
{
public class TaskApiController : ApiController
{
private readonly ITaskRepository taskRepository;
public TaskApiController()
{
taskRepository = new TaskRepository();
}
public IEnumerable<Task> Get()
{
return taskRepository.All;
}
public Task Get(int id)
{
var task = taskRepository.Find(id);
if (task == null)
{
throw new HttpResponseException(new HttpResponseMessage
{
StatusCode = HttpStatusCode.NotFound,
Content = new StringContent("Task not found")
});
}
return task;
}
public HttpResponseMessage Post(Task task)
{
taskRepository.InsertOrUpdate(task);
taskRepository.Save();
var response = Request.CreateResponse<Task>(HttpStatusCode.Created, task);
string uri = Url.Route(null, new { id = task.Id });
response.Headers.Location = new Uri(Request.RequestUri, uri);
return response;
}
public Task Put(Task task)
{
try
{
taskRepository.InsertOrUpdate(task);
taskRepository.Save();
}
catch (Exception)
{
throw new HttpResponseException(new HttpResponseMessage
{
StatusCode = HttpStatusCode.NotFound,
Content = new StringContent("Task not found")
});
}
return task;
}
public HttpResponseMessage Delete(int id)
{
taskRepository.Delete(id);
taskRepository.Save();
return new HttpResponseMessage
{
StatusCode = HttpStatusCode.NoContent
};
}
}
}
以上是关于csharp Nancy和ASP.NET Web API比较的主要内容,如果未能解决你的问题,请参考以下文章
csharp 自托管ASP.NET Web API的示例
csharp 在ASP.NET Web Api有效负载中添加资源链接
用Web api /Nancy 通过Owin Self Host简易实现一个 Http 服务器
自托管 asp.net mvc
csharp ASP.NET Web API:通过提供自己的AssembliesResolver来控制加载的程序集
csharp 将Castle Windsor依赖项注入ASP.NET Web API过滤器C#