0

我的 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);  

            }
        }
    }
4

1 回答 1

1

尝试在响应中设置内容类型:

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;
        }
    }
}
于 2016-08-31T07:05:01.067 回答