[英]ASP.Net Web API Return Specifc Error Data on Exception?
.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(不使用querystring值):
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>
僅對於此控制器,我想捕獲querystring參數錯誤的事實,並返回-1。 還有另一個控制器也不使用querystring參數。 有人可以引導我朝正確的方向前進嗎?
謝謝。
盡管它確實有效,但這並不是最優雅的解決方案:
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操作來捕獲所有到控制器的獲取並在那里返回-1。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.