ASP.Net Web API 在异常时返回特定的错误数据

本文关键字:返回 错误数据 异常 Net Web API ASP | 更新日期: 2023-09-27 18:18:24

.NET 4.5.2,具有以下路由信息设置:

public void Configuration( IAppBuilder appBuilder )
{
    var conf = new HttpConfiguration();
    conf.Routes.MapHttpRoute(
        name: "DefaultApi" ,
        routeTemplate: "service/2014/{controller}/{appKey}" , 
        defaults: new { appKey = RouteParameter.Optional }
    );
    appBuilder.UseWebApi( conf );
}

并使用以下控制器代码:

public HttpResponseMessage Get( string appKey , string qs1 , string qs2 )
{
    var remess = new HttpResponseMessage { RequestMessage = Request , StatusCode = HttpStatusCode.OK };
    if ( true == new BusinessClass().ValueCheck( appKey , qs1 , qs2 ) )
    {
        remess.Content =  new StringContent( "1" , Encoding.UTF8 , "text/plain");
    }
    else
    {
        remess.Content =  new StringContent( "0" , Encoding.UTF8 , "text/plain");
    }
    return remess;
}

如果我使用此 URI,它会根据业务逻辑正确返回"0"或"1":

http://localhost:963/service/2014/foo/appgo1?qs1=a&qs2=b

如果我使用此 URI(省略查询字符串值(:

http://localhost:963/service/2014/foo/appgo1

我收到一条框架控制的消息:

<Error> <Message> No HTTP resource was found that matches the request
URI 'http://localhoost:963/service/2014/foo/appgo1'.
</Message> <MessageDetail> No action was found on the controller
'foo' that matches the request. </MessageDetail> </Error>

仅对于此控制器,我想捕获查询字符串参数错误的事实并返回 -1。还有另一个控制器也根本不采用查询字符串参数。谁能引导我朝着正确的方向前进?

谢谢。

ASP.Net Web API 在异常时返回特定的错误数据

这不是最优雅的解决方案,尽管它确实有效:

    public HttpResponseMessage Get(string appKey, string qs1 = null, string qs2 = null)
    {
        var remess = new HttpResponseMessage { RequestMessage = Request, StatusCode = HttpStatusCode.OK };
        if (qs1 == null || qs2 == null)
        {
            remess.Content = new StringContent("-1", Encoding.UTF8, "text/plain");
        }
        else if ( true == new BusinessClass().ValueCheck( appKey , qs1 , qs2 ) )
        {
            remess.Content = new StringContent("1", Encoding.UTF8, "text/plain");
        }
        else
        {
            remess.Content = new StringContent("0", Encoding.UTF8, "text/plain");
        }
        return remess;
    }

您基本上将查询字符串参数设置为可选,然后检查其中任何一个是否为 null 以返回 -1 代码。否则,请执行业务逻辑检查。

您还可以使用默认的 GET 操作来捕获所有到控制器的 get 并在那里返回 -1。