簡體   English   中英

關於mvc4 web api

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM