2017-06-29 2 views
0

私は、MVC(Asp.net 4.5.2)のApiControllerでapiを実装しています。そのAPIでは、HttpResponseExceptionをHttpResponseMessage(HttpStatusCode.Unauthorized)でスローし、ReasonPhraseを指定したいと考えています。 asp/mvcをログインページにリダイレクトしようとするのではなく、クライアントに直接これを送ることができますか?クライアントに直接HTTPResponseExceptionをスローする

答えて

0

Asp.Netフォーム認証モジュール401あなたがUseCookieAuthenticationを使用する場合302

に、次いでOnApplyRedirect変更することによって、これを抑える変換

ファイルStartup.Auth.cs - > ConfigureAuth方法- > app.UseCookieAuthentication内部(新しいCookieAuthenticationOptions {プロバイダー=新しいCookieAuthenticationProvider {- >追加OnApplyRedirect

 app.UseCookieAuthentication(new CookieAuthenticationOptions 
     { 
      Provider = new CookieAuthenticationProvider 
      { 
       OnApplyRedirect = context => 
       { 
        if (!context.Request.Uri.LocalPath.StartsWith(VirtualPathUtility.ToAbsolute("~/api"))) 
        { 
         context.Response.Redirect(context.RedirectUri); 
        } 
       } 
      } 
     }); 
+0

私はあなたの指示を完全に理解しているとは思わない。私はSnippetをConfigureAuth(app)の直下のStartup.Configuration(IAppBuilder app)に追加しましたが、まだログインするようにリダイレクトされています。 – Roger

+0

startup.configuration以下ではありません。 startup.auth.csファイルにアクセスしてください。 line app.UseCookieAuthenticationを検索します。 UseCookieAuthenticationの内部で、プロバイダを設定すると、このコードを貼り付けてコピーします(OnApplyRedirectをオーバーライドします)。 – Kaushal

+0

ああ、はい。ありがとう、これは私が必要としていたものです。 APIはauthまたはapiエラーで詳細な説明を返すようになり、残りのアプリケーションの認証は変更されません。 – Roger

1
var message = new HttpResponseMessage(HttpStatusCode.Unauthorized); 
message.ReasonPhrase = "Hello"; 
throw new HttpResponseException(message); 

ただし、リダイレクトはWeb.configの設定によって異なります。あなたはこのセクションを削除した場合、リダイレクトは発生しません

<system.web> 
    <authentication mode="Forms"> 
    <forms loginUrl="/Login/Index"></forms> 
    </authentication> 
    </system.web> 

:私はあなたがこのようなweb.configファイルのsomethinkでの認証部を持っていると思います。しかし、この場合は、独自に認証を実装する必要があります。

+0

はい、まさに私がやっていることです。しかし、クライアントがエラーメッセージを受け取る代わりに、ログインページにバウンスされます。私はAPIを呼び出すクライアントがエラーを取得したい。 – Roger

+0

サーバー側またはクライアント側でhappendをリダイレクトする場所はどこですか? –

+0

私が理解している限り、mvcはUnauthorizedステータスコードを見て、リクエストをログインページにルーティングします。私はそれがエラーを返すだけです。 – Roger

関連する問題