0

У меня есть атрибут пользовательской авторизации для моего веб-API. Я хочу показать страницу, не найденную ресурсом, если моя ссылка API доступна напрямую из браузера. Это можно сделать?Как перенаправить взгляд из пользовательского фильтра авторизации Web 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); 

      } 
     } 
    } 

ответ

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; 
     } 
    } 
} 
+0

Приветствия, работает как шарм –