如何在MVC WebApi中使用自定义消息更改默认响应消息?
{ "Message": "Authorization has been denied for this request." }
提前感谢
您必须创建一个从AuthorizeAttribute
派生的类并重写HandleUnauthorizedRequest
方法。这样的事情(注意:这未经测试):
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Controllers;
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
{
if (!IsAuthorized(actionContext))
{
actionContext.Response = actionContext.Request.CreateErrorResponse(
HttpStatusCode.Forbidden,
"Custom message goes here");
}
}
}
然后在任何使用AuthorizeAttribute
的地方,都将其替换为MyAuthorizeAttribute
。