在查看ASP.NET Web API中的文章异常处理之后,我对于何时抛出异常vs返回错误响应感到困惑.我还想知道当你的方法返回特定于域的模型而不是HttpResponseMessage
... 时是否可以修改响应
所以,在这里回顾一下我的问题,然后是一些带有#s的代码:
HttpResponseMessage
而不是具体的域模型,以便可以自定义消息吗?HttpResponseException
VS有Request.CreateErrorResponse
什么区别?输出到客户端似乎相同......HttpError
"包装"错误中的响应消息(是否抛出异常或返回错误响应)?// CASE #1
public Customer Get(string id)
{
var customer = _customerService.GetById(id);
if (customer == null)
{
var notFoundResponse = new HttpResponseMessage(HttpStatusCode.NotFound);
throw new HttpResponseException(notFoundResponse);
}
//var response = Request.CreateResponse(HttpStatusCode.OK, customer);
//response.Content.Headers.Expires = new DateTimeOffset(DateTime.Now.AddSeconds(300));
return customer;
}
// CASE #2
public HttpResponseMessage Get(string id)
{
var customer = _customerService.GetById(id);
if (customer …
Run Code Online (Sandbox Code Playgroud) 我正在使用asp.net WebAPI,我需要创建一个自定义ActionFilter,它会快速检查请求URI的用户是否真的能够获取数据.
他们已被授权通过基本身份验证使用Web服务,并且他们的角色已通过自定义角色提供程序进行验证.
我需要做的最后一件事是检查他们是否有权使用URI中的参数查看他们请求的数据.
这是我的代码:
public class AccessActionFilter : FilterAttribute, IActionFilter
{
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> ExecuteActionFilterAsync(HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken, Func<System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>> continuation)
{
var result = //code to see if they have permission returns either 0 or 1
if (result==0) {
throw new ArgumentException("You do not have access to this resource");
}
return continuation();
}
}
Run Code Online (Sandbox Code Playgroud)
目前我只是抛出一个不是我想要的错误,我宁愿回来,System.Net.HttpStatusCode.Unauthorized
但我对我压倒的方法感到有点恼火,我完全不理解它.
我该如何回归这个价值?
我正在尝试从我的应用程序返回适当的Http代码和响应,但我正在努力.似乎有两种方法可以返回特定的http响应.
我想要处理它的方式是扔一个HttpResponseException
:
public Information Get(int apiKey)
{
if (!_users.Authenticate(apiKey))
{
var response = new HttpResponseMessage();
response.StatusCode = (HttpStatusCode)401;
response.ReasonPhrase = "ApiKey invalid";
throw new HttpResponseException(response);
}
return _info.Get();
}
Run Code Online (Sandbox Code Playgroud)
但是,当我这样做时,我看到的响应只是一个空的200响应!
您似乎也可以更改操作方法的签名以返回HttpResponseMessage
如下所示:
public HttpResponseMessage Get()
{
if (!_users.Authenticate(apiKey))
{
return Request.CreateResponse((HttpStatusCode) 401, "ApiKey invalid");
}
return Request.CreateResponse((HttpStatusCode) 200, _info.Get());
}
Run Code Online (Sandbox Code Playgroud)
我真的不想这样做,如果我可以帮助它,我宁愿把我的返回类型作为我试图检索的对象而不是每次都包装它HttpResponseMessage
.
有没有理由为什么第一个方法返回一个空的200而不是401我想要它的消息?