如何从Catch块返回错误信息。现在返回空 [英] How to return error message from Catch block. Right now empty is returned

查看:532
本文介绍了如何从Catch块返回错误信息。现在返回空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ApiKey验证我的示例code为如下(我用MVC4网页API RC):

My sample code of ApiKey validation is given below (I am using MVC4 web api RC):

public class ApiKeyFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext context)
    {
        //read api key from query string
        string querystring = context.Request.RequestUri.Query;
        string apikey = HttpUtility.ParseQueryString(querystring).Get("apikey");

        //if no api key supplied, send out validation message
        if (string.IsNullOrWhiteSpace(apikey))
        {                
            var response = context.Request.CreateResponse(HttpStatusCode.Unauthorized, new Error { Message = "You can't use the API without the key." });
            throw new HttpResponseException(response);
        }
        else
        {          
             try
            {
                GetUser(decodedString); //error occurred here
            }
            catch (Exception)
            {
                var response = context.Request.CreateResponse(HttpStatusCode.Unauthorized, new Error { Message = "User with api key is not valid" });
                throw new HttpResponseException(response);
            }
        }
    }
}

下面的问题是与Catch块声明。我只是想发送自定义错误消息用户。但没有什么是发送。它显示了一个空白页面

Here problem is with Catch block statement. I Just wanted to send custom error message to user. But nothing is sent. It displays a blank screen

但是,下面的语句是运作良好,并正确地发送了验证错误消息:

However, the statement below is working well and sends out the validation error message correctly:

if (string.IsNullOrWhiteSpace(apikey))
{                
    var response = context.Request.CreateResponse(HttpStatusCode.Unauthorized, new Error { Message = "You can't use the API without the key." });
    throw new HttpResponseException(response);
}

有什么,我做错了。

Is there anything that i am doing wrong.

推荐答案

我是有在完全相同的情况相同的问题。然而,在这种情况下,你需要返回你的回应一些内容中显示,并没有真正抛出异常。因此,在此基础上,我会改变你的code以下内容:

I was having the same issue in the exact same scenario. However, in this scenario, you need to return some content in your response to be shown and not really throw the exception. So based on this, I would change your code to the following:

 catch (Exception)
 {
    var response = context.Request.CreateResponse(httpStatusCode.Unauthorized);
    response.Content = new StringContent("User with api key is not valid");
    context.Response = response;
 }

因此​​,与将显示在地方黑屏的这种变化,现在你正在返回你的回应,与内容。

So with this change you are now returning your response, with content that will displayed in place of the blank screen.

这篇关于如何从Catch块返回错误信息。现在返回空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆