从ASP.Net Web API控制器操作重定向

nli*_*ips 2 asp.net redirect http-headers

我的api控制器需要使用2个参数实现一个简单的GET操作:ItemID和SectionID.返回类型ItemInSection包含有关该部分中项目的数据.

同一个项目可以分为多个部分.这就是需要SectionID的原因.

如果该项目已被移动并且不再在相应的部分中,我需要返回一个重定向代码301,其中的位置URL对应于包含该项目的一个部分.

做这个的最好方式是什么?

对于其他错误(例如404,401 ...)代码,我使用HttpResponseException.但对于301的情况,如何指定重定向url?

nli*_*ips 5

解决方案就是使用HttpResponseException(HttpResponseMessage response)构造函数(而不是简单的构造函数HttpStatusCode).

写吧:

HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Moved);
response.Headers.Location = ...;
throw new HttpResponseException(response);
Run Code Online (Sandbox Code Playgroud)