我正在开发一个 ASP.NET Web 应用程序,其中包含 MVC 和 WEB API。谁能给我一个如何在 Web API 中使用 ApiController.Unauthorized 方法的示例。我不确定应该将什么样的参数传递给这个方法。
最佳答案
如果您的 Controller 操作方法返回 IHttpActionResult
那么你可以使用这个方法作为返回类型。
return Unauthorized();
您也可以通过<a href="https://msdn.microsoft.com/en-us/library/system.net.http.headers.authenticationheadervalue(v=vs.118).aspx" rel="noreferrer noopener nofollow">AuthenticationHeaderValue</a>
作为此方法的参数,它表示 Authorization、ProxyAuthorization、WWW-Authneticate 和 Proxy-Authenticate header 值中的身份验证信息。
如果您的操作方法不返回 IHttpActionResult
那么你可以抛出 <a href="https://msdn.microsoft.com/en-us/library/system.web.http.httpresponseexception.aspx" rel="noreferrer noopener nofollow">HttpResponseException</a>
在 Controller 操作的任何地方。
throw new HttpResponseException(HttpStatusCode.Unauthorized);
如果您想传递自定义消息,请使用
var msg = new HttpResponseMessage(HttpStatusCode.Unauthorized)
{
ReasonPhrase = "Your message!"
};
throw new HttpResponseException(msg);
关于asp.net - 网络API 2.2 : ApiController Unauthorized Method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27124762/