简体   繁体   English

处理错误ASP.NET Web API

[英]Handling error ASP.NET Web API

I am creating an ASP.NET Web API method. 我正在创建一个ASP.NET Web API方法。 The web method accepts four input parameters which are used in querying an Oracle Database and returns the result in JSON. Web方法接受用于查询Oracle数据库的四个输入参数,并以JSON返回结果。 The input parameters are of type string and DateTime. 输入参数的类型为字符串和日期时间。 The API call looks like ?id=123&date_in=01-JAN-16 . API调用类似于?id=123&date_in=01-JAN-16 In the controller I have to handle validation errors such as id is null in the API call or the date format is different other than dd-MMM-yy and return an appropriate error message. 在控制器中,我必须处理验证错误,例如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;

Should I create a different class for handling these exceptions? 是否应该创建其他类来处理这些异常? How should I be returning the responses? 我应该如何返回答复?

Try Below Code 尝试以下代码

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

We can extend ExceptionFilterAttribute and create a custom exception filter attribute. 我们可以扩展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);
    }
}

And use it in the ApiController for returning the vliadation message. 并在ApiController中使用它来返回验证消息。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM