如何从自定义授权过滤器 Web Api 重定向到视图
How to redirect to a view from Custom Authorization filter Web Api
我的网站有一个自定义授权属性 API。如果直接从浏览器访问我的 API link,我想显示资源未找到页面。这能做到吗?
到目前为止,我已经设法对 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;
}
}
}
我的网站有一个自定义授权属性 API。如果直接从浏览器访问我的 API link,我想显示资源未找到页面。这能做到吗?
到目前为止,我已经设法对 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;
}
}
}