首页 文章

处理错误ASP.NET Web API

提问于
浏览
0

我正在创建一个ASP.NET Web API方法 . Web方法接受四个输入参数,这些参数用于查询Oracle数据库并以JSON格式返回结果 . 输入参数的类型为string和DateTime . 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;

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

2 回答

  • 0

    尝试以下代码

    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;
                }
                }
    
  • 0

    我们可以扩展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");
            }
            //...
    }
    

相关问题