返回特定HTTP状态code在行动GET请求 [英] Return specific HTTP status code in action for GET request
问题描述
我使用的ASP.NET Web API创建REST服务。
我怎样才能返回401状态code从行动GET方法...
I'm creating REST service using ASP.NET Web API. How can I return 401 status code from action for GET method...
我没有问题,例如从返回一些状态code POST方法,因为我可以返回类型设置为Htt的presponseMessage
I don't have problem with returning some status code from e.g. POST method, cause I can set the return type to 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;
}
}
但是,我怎么能返回状态code为GET方法,当方法比Htt的presponseMessage返回不同的类型:
However, how can I return the status code for GET method, when the method returns different type than HttpResponseMessage:
public Car Get(int id)
{
var context = new CarEntities();
return context.Cars.Where(p => p.id == id).FirstOrDefault();
}
我想例如返回401当在此Get方法授权失败
I would like to return e.g. 401 when authorization in this Get method failed
感谢
推荐答案
您应该抛出一个<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.http.htt$p$psponseexception%28v=vs.108%29.aspx\"><$c$c>Htt$p$psponseException$c$c>,它允许你指定响应code,例如:
You should throw a HttpResponseException
, which allows you to specify the response code, for example:
if (authFailed) {
throw new HttpResponseException(HttpStatusCode.Unauthorized);
}
这篇关于返回特定HTTP状态code在行动GET请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!