2016-02-23 13 views
7

C# Web API 2'yi kullanarak, bir InvalidOperationException atar kodum var. 302 durum kodunu döndürürken, HandleException ek açıklamasını kullanarak yönlendirme için bir konum nasıl sağlanır?302 durum kodu için handexeption ek açıklamasını kullanırken konumu nasıl belirlersiniz?

[HandleException(typeof(InvalidOperationException), HttpStatusCode.Found, ResponseContent = "Custom message 12")] 
public IHttpActionResult GetHandleException(int num) 
{ 
    switch (num) 
    { 
      case 12: throw new InvalidOperationException("DONT SHOW invalid operation exception"); 

      default: throw new Exception("base exception"); 
    } 
} 

Düzenleme: Üzgünüm, acele biraz bu soru soruldu. Yukarıdaki sınıf, ExceptionFilterAttribute öğesinden devralınan bir HandleExceptionAttribute sınıfı kullanır. Bunu, ünite testlerinde hata ayıklamaya çalıştığım zaman fark etmedim. Sorun bir birim sınamasında ortaya çıkmaz, ancak yönlendirme URL'si gerektiren bir Visual Studio .webtest kullanarak ortaya çıkar. ExceptionFilterAttribute öğesinden devraldığı sınıf, yönlendirilen URL'nin sağlanmasına izin veren bir parametre sağlamaz. Tamamlanmamış bir soru için üzgünüm ve cevap vermek için zaman ayırdığınız için teşekkürler.

/// <summary> 
    /// This attribute will handle exceptions thrown by an action method in a consistent way 
    /// by mapping an exception type to the desired HTTP status code in the response. 
    /// It may be applied multiple times to the same method. 
    /// </summary> 
    [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = true)] 
    public sealed class HandleExceptionAttribute : ExceptionFilterAttribute 
    { 
+1

** HandleException ** özniteliği sizin mi? Kullanımını iyileştirmek için neler yapabileceğinizi görmek için kaynak kodunu veya kaynağı bağlantılandırabilir misiniz? – D4rkTiger

+1

İstisna filtresi kullanın ve yönlendirme mantığınızı buradan ayarlayın. Filtrelere koşul tabanlı yönlendirme de koyabilirsiniz. –

+0

Size uygun bir yanıtla size yardımcı olacak daha fazla bilgi verin. –

cevap

3

Düzenlendi: Teşekkürler için soru güncellendi. Hala bu WebApi yönteminde neden yeniden yönlendirmek istediğinizi tam olarak bilmiyorum. Umarım bu cevap yine de yardımcı olabilir.

Tüm özel durum mantığını HandleExceptionAttribute'de kullanırdım. Aradığın 302 koduyla oradan da yönlendirebilirsin. Eğer ikinci bir parametre ekleyerek bunu, gerçekten sormak şekilde yapılır istiyorum Ancak

public sealed class HandleExceptionAttribute : ExceptionFilterAttribute 
{ 
    public override void OnException(HttpActionExecutedContext context) 
    { 
     //TODO: we can handle all types of exceptions here. Out of memory, divide by zero, etc etc. 
     if (context.Exception is InvalidOperationException) 
     { 
      var httpResponseMessage = context.Request.CreateResponse(HttpStatusCode.Redirect); 
      httpResponseMessage.Headers.Location = new Uri("http://www.YourRedirectUrl"); 
      throw new HttpResponseException(httpResponseMessage); 
     } 
     if (context.Exception is UnauthorizedAccessException) 
     { 
      context.Response = context.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, context.Exception.Message); 
      return; 
     } 
     if (context.Exception is TimeoutException) 
     { 
      throw new HttpResponseException(context.Request.CreateResponse(HttpStatusCode.RequestTimeout, context.Exception.Message)); 
     } 

     context.Response = context.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unable to process your request."); 
    } 
} 

: Sizin HandleExceptionAttribute (ben bir istisna dayalı bir sonucu dönen 3 farklı yolları dahil ettik) şu şekilde görünecektir GetHandleException yönteminiz.

public IHttpActionResult GetHandleException(int num, string message = "") 
{ 
    switch (num) 
    { 
     case 12: return Redirect(message); //message string would be your url 

     default: throw new Exception("base exception"); 
    } 
} 

Sonra HandleExceptionAttribute şuna benzer: Bu daha sonra HandleExceptionAttribute size (ActionArguements) parametresine yönlendirme url eklersiniz bir mesaj dize (veya URL) 'de alacağını

public sealed class HandleExceptionAttribute : ExceptionFilterAttribute 
{ 
    public override void OnException(HttpActionExecutedContext context) 
    { 
     context.ActionContext.ActionArguments["message"] = "your redirect URL"; 

    } 
} 
+1

Kullanıcı, özel duruma göre belirli sayfalara yönlendirmek istiyor. –

+1

Soru biraz kafa karıştırıcı. Sadece istisna atmaya mı çalışıyorsun? Öyleyse, yeniden yönlendirmek istediğiniz konum gibi ek verilerle kendi başına özel bir istisna oluşturmaya ne dersiniz? – drunkcoder

+0

@TheEmirOfGroofunkistan Cevabımı güncellenmiş soruya göre güncelledim. –

0

Improvise aşağıdaki

public class HandleExceptionAttribute : ExceptionFilterAttribute 
{ 
    public Type ExceptionType { get; set; } 

    public HandleExceptionAttribute(Type exceptionType) 
    { 
     ExceptionType = exceptionType; 
    } 
    public override void OnException(HttpActionExecutedContext actionExecutedContext) 
    { 
     if (actionExecutedContext.Exception.GetType()==ExceptionType) 
     { 
      var response = actionExecutedContext.Request.CreateResponse(HttpStatusCode.Moved); 
      response.Headers.Location=new Uri("http://google.co.uk"); 
      response.Content=new StringContent("Message"); 
      actionExecutedContext.Response = response; 
     } 
     base.OnException(actionExecutedContext); 
    } 
} 

Kullanımı gelen

[HandleException(typeof(ExceptionOfTypeA))] 
    public HttpResponseMessage Get(int id) 
    { 
     throw new ExceptionOfTypeA(); 
    } 

Bu, görsel bir sayfaya yeniden yönlendirildiğinde orada içerik bulundurma noktasını görmüyorum. ama biz var

İlgili konular