【问题标题】:Handling error ASP.NET Web API处理错误 ASP.NET Web API
【发布时间】:2016-11-16 20:06:59
【问题描述】:

我正在创建一个 ASP.NET Web API 方法。 Web 方法接受四个输入参数,用于查询 Oracle 数据库并以 JSON 格式返回结果。输入参数的类型为字符串和日期时间。 API 调用类似于?id=123&date_in=01-JAN-16。在控制器中,我必须处理验证错误,例如 API 调用中的 id 为 null 或日期格式不同于 dd-MMM-yy 并返回适当的错误消息。

public class DataController : ApiController
{
    [HttpGet]
    public HttpResponseMessage Getdetails(string id,DateTime date_in)
        {
            List<OracleParameter> prms = new List<OracleParameter>();
            prms.Add(new OracleParameter("id", OracleDbType.Varchar2, id, ParameterDirection.Input));
            prms.Add(new OracleParameter("date_in", OracleDbType.Date, date_in, ParameterDirection.Input));
           string connStr = ConfigurationManager.ConnectionStrings["DtConnection"].ConnectionString;
        using (OracleConnection dbconn = new OracleConnection(connStr))
        {
            DataSet userDataset = new DataSet();
            var strQuery = "SELECT * from SAMPLE where id = :id and date_in = :date_in ";
            var returnObject = new { data = new OracleDataTableJsonResponse(connStr, strQuery, prms.ToArray()) };
            var response = Request.CreateResponse(HttpStatusCode.OK, returnObject, MediaTypeHeaderValue.Parse("application/json"));
            ContentDispositionHeaderValue contentDisposition = null;
            if (ContentDispositionHeaderValue.TryParse("inline; filename=TGSData.json", out contentDisposition))
            {
                response.Content.Headers.ContentDisposition = contentDisposition;
            }
            return response;

我应该创建一个不同的类来处理这些异常吗?我应该如何返回响应?

【问题讨论】:

  • 您可以使用类型化参数来防止对 id 进行空检查:Getdetails(int id, DateTime date_in),如果他们尝试执行类似 ?id= 之类的操作,这将从 ASP.NET 返回错误火烈鸟&date_in=01-JAN-16。至于错误处理,一种更简单的方法可能是创建一个 DelegatingHandler,它会在 try/catch 中调用 SendAsync 并在抛出异常时返回一致的错误消息。

标签: c# asp.net asp.net-web-api


【解决方案1】:

试试下面的代码

public class DataController : ApiController
            {
                [HttpGet]
                public HttpResponseMessage Getdetails(string id,DateTime date_in)
                {
                    if(id==string.Empty || id==null)
                    {
                      return "Id Value Should not Empty or Null";
                    }
                    if(!Regex.IsMatch(date_in, "^(([0-9])|([0-2][0-9])|([3][0-
                    1]))\-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\-
                    \d{4}$"))
                    {
                      return "Invalid Date Format";
                    }
                    List<OracleParameter> prms = new List<OracleParameter>();
                    prms.Add(new OracleParameter("id", OracleDbType.Varchar2,
                    id, ParameterDirection.Input));
                    prms.Add(new OracleParameter("date_in", OracleDbType.Date, date_in, ParameterDirection.Input));
                       string connStr = ConfigurationManager.ConnectionStrings["DtConnection"].ConnectionString;
                    using (OracleConnection dbconn = new OracleConnection(connStr))
                    {
                        DataSet userDataset = new DataSet();
                        var strQuery = "SELECT * from SAMPLE where id = :id and date_in = :date_in ";
                        var returnObject = new { data = new OracleDataTableJsonResponse(connStr, strQuery, prms.ToArray()) };
                        var response = Request.CreateResponse(HttpStatusCode.OK, returnObject, MediaTypeHeaderValue.Parse("application/json"));
                        ContentDispositionHeaderValue contentDisposition = null;
                        if (ContentDispositionHeaderValue.TryParse("inline; filename=TGSData.json", out contentDisposition))
                        {
                            response.Content.Headers.ContentDisposition = contentDisposition;
                        }
                        return response;
            }
            }

【讨论】:

  • 如果无法验证.. 尝试将参数数据类型 DateTime 替换为字符串数据类型。
【解决方案2】:

我们可以扩展ExceptionFilterAttribute 并创建自定义异常过滤器属性。

public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext context)
    {
        var exception = context.Exception; 
        context.Response = new HttpResponseMessage(System.Net.HttpStatusCode.InternalServerError);
        context.Response.Content = new StringContent(exception.Message);
    }
}

并在 ApiController 中使用它来返回 vliadation 消息。

[HttpGet]
[CustomExceptionFilterAttribute]
public HttpResponseMessage Getdetails(string id, DateTime date_in)
{
        if (string.IsNullOrEmpty(id))
        {
            throw new ArgumentNullException("id");
        }
        //...
}

【讨论】:

    猜你喜欢
    • 2013-10-23
    • 2019-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-27
    • 2016-10-27
    • 2012-05-04
    相关资源
    最近更新 更多