简体   繁体   中英

ASP.Net Web API Return Specifc Error Data on Exception?

.NET 4.5.2, with the following routing information setup:

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

And with the following controller code:

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

If I use this URI, it properly returns a "0" or a "1" based on the business logic:

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

If I use this URI (leaving off the querystring values):

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

I get a framework-controlled message:

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

For this controller only, I would like to trap the fact that the querystring parameters are wrong and return a -1 instead. There is another controller that does not take querystring parameters at all, as well. Can anyone steer me in the right direction on this?

Thanks.

This is not the most elegant solution though it does work:

    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;

    }

You basically make the query string params optional and then check if either is null to return your -1 code. Otherwise, do your business logic checks.

You could also have a default GET action to catch all gets to the controller and return -1 there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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