23

すべての 401 エラーをカスタム エラー ページにリダイレクトする必要があります。最初に web.config に次のエントリを設定しました。

<customErrors defaultRedirect="ErrorPage.aspx" mode="On">
  <error statusCode="401" redirect="~/Views/Shared/AccessDenied.aspx" />
</customErrors>

IIS Express を使用すると、在庫の IIS Express 401 エラー ページが表示されます。

IIS Express を使用しない場合、空白のページが返されます。Google Chrome の [ネットワーク] タブを使用して応答を調べると、ページが空白のときにヘッダーに 401 ステータスが返されることがわかります

IIS Expressを使用しているため、これまでに試したのはこのSOの回答からの提案を使用していますが、役に立ちませんでした。組み合わせ<custom errors>を使用してみました<httpErrors>が、うまくいきません - 標準エラーまたは空白のページがまだ表示されます。

セクションは、上記のSOの質問からのリンクhttpErrorsに基づいて、現時点では次のようになっています(別の非常に有望な回答も見つかりましたが、運がありません-空白の回答)

<system.webServer>
  <httpErrors  errorMode="DetailedLocalOnly" existingResponse="PassThrough" >
    <remove statusCode="401"  />
    <error statusCode="401" path="/Views/Shared/AccessDenied.htm" />
  </httpErrors>

 <!-- 
 <httpErrors  errorMode="Custom" 
             existingResponse="PassThrough" 
             defaultResponseMode="ExecuteURL">
      <remove statusCode="401"  />
  <error statusCode="401" path="~/Views/Shared/AccessDenied.htm" 
         responseMode="File" />
 </httpErrors>
 -->
</system.webServer>

applicationhost.configファイルを変更し<httpErrors lockAttributes="allowAbsolutePathsWhenDelegated,defaultPath">iis.net<httpErrors lockAttributes="allowAbsolutePathsWhenDelegated">からの情報に基づいて変更しました。私の努力の過程で、別の SO questionで説明されているように、このエラーに遭遇することもできました。

Asp.Net Mvc 3 でカスタム エラー ページを表示するにはどうすればよいですか?

追加情報

次のコントローラー アクションはAuthorize、特定のユーザーの属性で修飾されています。

[HttpGet]
[Authorize(Users = "domain\\userXYZ")]
public ActionResult Edit() 
{
   return GetSettings();
}

[HttpPost]
[Authorize(Users = "domain\\userXYZ")]
public ActionResult Edit(ConfigurationModel model, IList<Shift> shifts)
{
    var temp = model;
    model.ConfiguredShifts = shifts;
    EsgConsole config = new EsgConsole();

    config.UpdateConfiguration(model.ToDictionary());
    return RedirectToAction("Index");
}
4

4 に答える 4

34

次の手順を使用します。

// in Global.asax.cs:
        protected void Application_Error(object sender, EventArgs e) {

            var ex = Server.GetLastError().GetBaseException();

            Server.ClearError();
            var routeData = new RouteData();
            routeData.Values.Add("controller", "Error");
            routeData.Values.Add("action", "Index");

            if (ex.GetType() == typeof(HttpException)) {
                var httpException = (HttpException)ex;
                var code = httpException.GetHttpCode();
                routeData.Values.Add("status", code);
            } else {
                routeData.Values.Add("status", 500);
            }

            routeData.Values.Add("error", ex);

            IController errorController = new Kavand.Web.Controllers.ErrorController();
            errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
        }

        protected void Application_EndRequest(object sender, EventArgs e) {
            if (Context.Response.StatusCode == 401) { // this is important, because the 401 is not an error by default!!!
                throw new HttpException(401, "You are not authorised");
            }
        }

と:

// in Error Controller:
    public class ErrorController : Controller {

        public ActionResult  Index(int status, Exception error) {
            Response.StatusCode = status;
            return View(status);
        }

        protected override void Dispose(bool disposing) {
            base.Dispose(disposing);
        }
    }

AND エラー フォルダーのインデックス ビュー:

@* in ~/Views/Error/Index.cshtml: *@

@model Int32    
@{
    Layout = null;
}    
<!DOCTYPE html>    
<html>
<head>
    <title>Kavand | Error</title>
</head>
<body>
    <div>
        There was an error with your request. The error is:<br />
        <p style=" color: Red;">
        @switch (Model) {
            case 401: {
                    <span>Your message goes here...</span>
                }
                break;
            case 403: {
                    <span>Your message goes here...</span>
                }
                break;
            case 404: {
                    <span>Your message goes here...</span>
                }
                break;
            case 500: {
                    <span>Your message goes here...</span>
                }
                break;
            //and more cases for more error-codes...
            default: {
                    <span>Unknown error!!!</span>
                }
                break;
        }
        </p>
    </div>
</body>
</html>

AND - 最終ステップ:

<!-- in web.config: -->

<customErrors mode="Off"/>
于 2011-09-08T01:36:59.883 に答える
11

web.config と MVC で CustomErrors をうまく連携させることができなかったので、あきらめました。代わりにこれを行います。

global.asax で:

protected void Application_Error()
    {
        var exception = Server.GetLastError();
        var httpException = exception as HttpException;
        Response.Clear();
        Server.ClearError();
        var routeData = new RouteData();
        routeData.Values["controller"] = "Errors";
        routeData.Values["action"] = "General";
        routeData.Values["exception"] = exception;
        Response.StatusCode = 500;
        if (httpException != null)
        {
            Response.StatusCode = httpException.GetHttpCode();
            switch (Response.StatusCode)
            {
                case 403:
                    routeData.Values["action"] = "Http403";
                    break;
                case 404:
                    routeData.Values["action"] = "Http404";
                    break;
            }
        }
        // Avoid IIS7 getting in the middle
        Response.TrySkipIisCustomErrors = true;
        IController errorsController = new GNB.LG.StrategicPlanning.Website.Controllers.ErrorsController();
        HttpContextWrapper wrapper = new HttpContextWrapper(Context);
        var rc = new RequestContext(wrapper, routeData);
        errorsController.Execute(rc);
    }

ErrorsController:

public class ErrorsController
{
    public ActionResult General(Exception exception)
    {
        // log the error here
        return View(exception);
    }

    public ActionResult Http404()
    {
        return View("404");
    }

    public ActionResult Http403()
    {
        return View("403");
    }
}

web.config:

<customErrors mode="Off" />

エラーがどこでどのように作成されても、それは私にとってはうまくいきました。401 は現在のところ処理されていませんが、簡単に追加できます。

于 2011-07-18T12:52:10.817 に答える
9

何かが足りないのかもしれませんが、MVC にErrorHandlerAttributeはカスタム エラーを使用するデフォルトのグローバルがあります。これはここで非常によく説明されています。

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new HandleErrorAttribute());
}

あなたがする必要があるのは、構成でオンにcustom errorsしてから、できれば静的HTMLファイルへのカスタム エラー リダイレクトをセットアップすることです (アプリにエラーがある場合)。

<customErrors mode="On" defaultRedirect="errors.htm">
    <error statusCode="404" redirect="errors404.htm"/>
</customErrors>

必要に応じて、カスタムControllerを指定してエラーを表示することもできます。Controller次の例では、 namedへのデフォルト ルーティングを使用Errorし、action をIndex、string パラメータを named id(エラーコードを受け取るため) にしました。もちろん、任意のルーティングを使用できます。Viewsを経由せずにディレクトリに直接リンクしようとしているため、例は機能しませんControllerViewsMVC .NET は、フォルダーへの要求を直接処理しません。

<customErrors mode="On" defaultRedirect="/error/index/500">
    <error statusCode="404" redirect="/error/index/404"/>
</customErrors>

ErrorHandlerAttributeを広範囲に使用してControllers/Actions、エラーを にViews関連する名前付きにリダイレクトすることもできますController。たとえば、タイプの例外が発生したときにView名前付きを表示するには、次を使用できます。MyArgumentErrorArgumentException

[ControllerAction,ExceptionHandler("MyArgumentError",typeof(ArgumentException))]
public void Index()
{
   // some code that could throw ArgumentExcepton
}

もちろん、別のオプションは の在庫Errorページを更新することSharedです。

于 2011-09-09T23:28:56.997 に答える
0

そこにある web.config の最初の部分を見ると、.aspx ページを直接指しています。エラーページをセットアップするとき、コントローラーとアクションを直接示しました。例えば:

<customErrors mode="On" defaultRedirect="~/Error/UhOh">
  <error statusCode="404" redirect="~/Error/NotFound" />
  <error statusCode="403" redirect="~/Error/AccessDenied" />
</customErrors>

そして、必要なすべてのアクションを備えたエラーコントローラーがありました。MVC は、.aspx ページへの直接呼び出しではうまく機能しないと思います。

于 2011-09-14T00:31:39.413 に答える