如何添加自定义异常/错误?

时间:2014-03-04 16:29:29

标签: c# error-handling asp.net-web-api basic-authentication

当用户将用户名/密码留空或在登录对话框中按“取消”时,我想添加错误或异常,这些错误或异常会显示在cliet端。目前,它显示那些例外的空白屏幕。

public class BasicAuthHandler : DelegatingHandler
 {
    private const string BasicAuthResponseHeader = "WWW-Authenticate";
    private const string BasicAuthResponseHeaderValue = "Basic";

    public BasicAuthHandler(iUser repository)
    {
        this.repository = repository;
    }

    [Inject]
    iUser repository { get; set; }


    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        AuthenticationHeaderValue authValue = request.Headers.Authorization;


        if (authValue == null || authValue.Scheme != BasicAuthResponseHeaderValue)
        {
            return Unauthorized(request);
        }
        string[] credentials = Encoding.ASCII.GetString(Convert.FromBase64String(authValue.Parameter)).Split(new[] { ':' });
        if (credentials.Length != 2 || string.IsNullOrEmpty(credentials[0]) || string.IsNullOrEmpty(credentials[1]))
        {
            return Unauthorized(request);

        }
        api_login user = repository.Validate2(credentials[0], credentials[1]);
        if (user == null)
        {
            return Unauthorized(request);
        }
        string[] roles = new[] { "Users", "Testers" };
        IPrincipal principal = new GenericPrincipal(new GenericIdentity(user.username, BasicAuthResponseHeaderValue), roles);
        Thread.CurrentPrincipal = principal;
        HttpContext.Current.User = principal;

        return base.SendAsync(request, cancellationToken);
    }

    private Task<HttpResponseMessage> Unauthorized(HttpRequestMessage request)
    {
        var response = request.CreateResponse(HttpStatusCode.Unauthorized);
        response.Headers.Add(BasicAuthResponseHeader, BasicAuthResponseHeaderValue);
        var task = new TaskCompletionSource<HttpResponseMessage>();
        task.SetResult(response);
        return task.Task;
    }

    private api_login ParseAuthorizationHeader(string authHeader)
    {
        string[] credentials = Encoding.ASCII.GetString(Convert.FromBase64String(authHeader)).Split(new[] { ':' });
        if (credentials.Length != 2 || string.IsNullOrEmpty(credentials[0]) || string.IsNullOrEmpty(credentials[1])) return null;

        return new api_login()
        {
            username = credentials[0],
            password = credentials[1],
        };
    }

更新了错误代码:

 protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        AuthenticationHeaderValue authValue = request.Headers.Authorization;

        if (authValue == null || authValue.Scheme != BasicAuthResponseHeaderValue)
        {
            return Unauthorized(request);
        }

        string[] credentials = Encoding.ASCII.GetString(Convert.FromBase64String(authValue.Parameter)).Split(new[] { ':' });
        if (credentials.Length != 2 || string.IsNullOrEmpty(credentials[0]) || string.IsNullOrEmpty(credentials[1]))
        {
           //return Unauthorized(request);
           var resp = new HttpResponseMessage(HttpStatusCode.NotFound)
           {
               Content = new StringContent(string.Format("access denied")),
           };
        }

        api_login user = repository.auth(credentials[0], credentials[1]);
        if (user == null)
        {
           //return Unauthorized(request);
           //return request.CreateErrorResponse(HttpStatusCode.NotFound, "If not member, please sign in using:");
           var resp = new HttpResponseMessage(HttpStatusCode.NotFound)
           {
               Content = new StringContent(string.Format("access denied")),
           };

        }

        var roles = repository.GetRolesForUser(user.username);
        IPrincipal principal = new GenericPrincipal(new GenericIdentity(user.username, BasicAuthResponseHeaderValue), roles);
        Thread.CurrentPrincipal = principal;
        HttpContext.Current.User = principal;

        return base.SendAsync(request, cancellationToken)
        .ContinueWith(task =>
       {
           var response = task.Result;

           if (response.StatusCode == HttpStatusCode.Unauthorized
               && !response.Headers.Contains(BasicAuthResponseHeader))
           {
               // redirect to some log in page?
               var resp = new HttpResponseMessage(HttpStatusCode.NotFound)
               {
                   Content = new StringContent(string.Format("access denied")),
               };
           }
           return response;
       });
    }

我不确定在代码中添加异常的正确方法,我在上面的代码中添加了几个错误代码,但每当我在登录对话框上按取消时,它会转到空白屏幕而不是显示以下内容错误消息。

非常感谢任何帮助。 谢谢

0 个答案:

没有答案