[英]Regarding mvc4 web api
HEllo这是一些mvc4 webapi代码,任何人都可以在这里解释我的每一行代码..我用谷歌搜索但没有找到任何有趣的东西
public HttpResponseMessage PostProduct(Product item)
{
item = repository.Add(item);
var response = Request.CreateResponse(HttpStatusCode.Created, item);
string uri = Url.RouteUrl("DefaultApi", new { id = item.Id });
response.Headers.Location = new Uri(uri);
return response;
}
我只知道我正在发送产品项目..作为回报,这个web api给我回复了新添加的产品,但我不明白这两行特别是
string uri = Url.RouteUrl("DefaultApi", new { id = item.Id });
response.Headers.Location = new Uri(uri);
public HttpResponseMessage PostProduct(Product item)
{
//creates and adds an item to repository(db)
item = repository.Add(item);
//creates a new httpresponse
var response = Request.CreateResponse(HttpStatusCode.Created, item);
//creates new uri
string uri = Url.RouteUrl("DefaultApi", new { id = item.Id });
//set header for new uri
response.Headers.Location = new Uri(uri);
return response;
}
这行将创建一个新的RouteUrl - >基本上是响应头的链接。
我的建议是你应该从这里的官方文档开始: http : //www.asp.net/web-api ,它对我有用。 这里有很多东西需要研究: http : //geekswithblogs.net/JoshReuben/archive/2012/10/28/aspnet-webapi-rest-guidance.aspx
这个答案中有太多的例子可以帮到你。
·响应代码:默认情况下,Web API框架将响应状态代码设置为200(OK)。 但根据HTTP / 1.1协议,当POST请求导致创建资源时,服务器应回复状态201(已创建)。 非Get方法应该返回HttpResponseMessage
·位置:当服务器创建资源时,它应该在响应的Location头中包含新资源的URI。
public HttpResponseMessage PostProduct(Product item) { item = repository.Add(item); var response = Request.CreateResponse<Product>(HttpStatusCode.Created, item); string uri = Url.Link("DefaultApi", new { id = item.Id }); response.Headers.Location = new Uri(uri); return response; }
public HttpResponseMessage PostProduct(Product item)
//this means that any post request to this controller will hit this action method
{
item = repository.Add(item);
//the posted data would be added to the already defined repository
var response = Request.CreateResponse(HttpStatusCode.Created, item);
//a responses is created with code 201. which means a new resource was created.
string uri = Url.RouteUrl("DefaultApi", new { id = item.Id });
//you get a new url which points to the route names DefaultAPI and provides a url parameter id(normally defined as optional)
response.Headers.Location = new Uri(uri);
//adds the created url to the headers to the response
return response;
//returns the response
}
通常,作为标准,POST请求用于创建实体。 并且随该请求一起发送要放入该实体的数据。
所以这里的代码是创建实体,然后在响应中发送回您可以找到最近创建的实体的URL。 这是任何客户都期望谁遵循标准。 虽然这不是必要的。
所以根据这个你必须有一个GET
动作方法,它接受id
作为参数,并返回与该id
对应的product
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.