3

您好,这是一段 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 会返回我对新添加产品的响应,但我特别不理解这 2 行

 string uri = Url.RouteUrl("DefaultApi", new { id = item.Id });
        response.Headers.Location = new Uri(uri);
4

2 回答 2

4
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:服务器创建资源时,应在响应的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;
}
于 2013-03-30T06:35:42.230 回答
2
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。这是任何遵循标准的客户所期望的。尽管这根本没有必要。

so according to this you must have a GET action method that accepts the id as an parameter and returns the product corresponding to that id

于 2013-03-30T06:53:13.273 回答