0

Web 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

乾杯 –

関連する問題