2012-03-24 122 views
2

我正在使用ASP.NET Web API創建REST服務。 如何從GET方法的動作返回401狀態碼...返回GET請求的特定HTTP狀態代碼

我沒有問題,例如返回一些狀態代碼。 POST方法,因爲我可以將返回類型HttpResponseMessage

public HttpResponseMessage Post(Car car) 
    { 
     using (var context = new CarEntities()) 
     { 
      ... 
      var response = new HttpResponseMessage(HttpStatusCode.Created); 
      response.Headers.Location = new Uri(Request.RequestUri, path); 
      return response; 
     } 
    } 

但是,我怎麼能返回的狀態代碼,GET方法,當該方法返回的類型不同於HttpResponseMessage:

public Car Get(int id) 
{ 

    var context = new CarEntities(); 
    return context.Cars.Where(p => p.id == id).FirstOrDefault(); 
} 

我會喜歡返回例如401當在此Get方法授權失敗

感謝

+0

我沒有看到任何認證回事在行動中。這個認證會在哪裏發生?如果您需要在多個操作中執行此操作,我會考慮使用Authentication屬性並根據需要裝飾操作? – dreza 2012-03-24 20:22:51

回答

5

你應該拋出一個HttpResponseException,它允許你指定的響應代碼,例如:

if (authFailed) { 
    throw new HttpResponseException(HttpStatusCode.Unauthorized); 
}