如何从自定义授权过滤器Web Api重定向到视图
本文关键字:Api 重定向 视图 Web 过滤器 自定义 授权 | 更新日期: 2023-09-27 18:04:54
我有一个自定义授权属性为我的web API。我想显示资源未找到的页面,如果我的API链接是直接从浏览器访问。这能做到吗?
到目前为止,我已经设法编码在HttpResponse消息中找不到的资源。我试图使用字符串内容,并把html标签,但它不工作。还有别的办法吗?
public class CustomAuthorizeAttribute: AuthorizeAttribute
{
public CustomAuthorizeAttribute(): base()
{
}
protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
{
if (!(System.Web.HttpContext.Current.User).Identity.IsAuthenticated)
{
actionContext.Response = new HttpResponseMessage(HttpStatusCode.NotFound);
string message = "<!DOCTYPE html><html><head><title> Page Not Found </title></head><bod>";
message+= "< h2 style = 'text-align:center'> Sorry, Page Not Found </ h2 ></body></html> ";
actionContext.Response.Content = new StringContent(message);
}
}
}
尝试设置响应的内容类型:
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
public CustomAuthorizeAttribute() : base()
{
}
protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
{
if (!actionContext.RequestContext.Principal.Identity.IsAuthenticated)
{
var response = new HttpResponseMessage(HttpStatusCode.NotFound);
string message =
"<!DOCTYPE html><html><head><title> Page Not Found </title></head><body><h2 style='text-align:center'> Sorry, Page Not Found </h2></body></html>";
response.Content = new StringContent(message);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
actionContext.Response = response;
}
}
}