HttpResponseException不接受HttpStatusCode

hof*_*lie 8 c# asp.net http httpresponse asp.net-web-api

我正在尝试HttpResponseException按照此截屏视频中的描述进行提升(约1分钟)

throw new HttpResponseException(HttpStatusCode.Unauthorized);
Run Code Online (Sandbox Code Playgroud)

但该应用程序将无法编译,因为它会引发以下错误:

The best overloaded method match for 'System.Web.Http.HttpResponseException.HttpResponseException(System.Net.Http.HttpResponseMessage)' has some invalid arguments
Run Code Online (Sandbox Code Playgroud)

msdn上的文档说它有一个接受HttpResponseMessage枚举的构造函数.http://msdn.microsoft.com/en-us/library/hh835324%28v=vs.108%29.aspx

我错过了什么?

谢谢

sml*_*ync 11

如果你正在使用RC,这已经改变了.尝试:

throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Unauthorized));
Run Code Online (Sandbox Code Playgroud)

  • @Zote - 创建一个HttpResponseMessage变量,设置Content属性,然后传入HttpResponseException.或者如果你想变得非常花哨,我写了一篇关于[返回自定义错误类型]的帖子(http://smlync.tumblr.com/post/23104849655/returning-custom-error-data-type-in​​- ASP净网页API). (4认同)

Nic*_*sen 6

刚刚遇到这个问题,我很高兴看到smlync提供的答案,但令人失望的是看到这个案例中的API变得更加冗长!恕我直言,以下倾向于描述'怪异',特别是当这个例外(最重要的是)多次填充每个控制器时:

    throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
Run Code Online (Sandbox Code Playgroud)

我可能正在使用它,也许你们中的一些人会发现它也很有用:

    throw new Http404NotFoundException();
Run Code Online (Sandbox Code Playgroud)

如果你想要放置以下内容:

public class Http404NotFoundException : HttpResponseException
{
    public Http404NotFoundException()
        : base(new HttpResponseMessage(HttpStatusCode.NotFound)) { }
}
Run Code Online (Sandbox Code Playgroud)

这不是更清洁,深受喜爱的ASP.NET WebApi团队吗?如果仅针对此状态代码,可能会引入其他几个非常常见的状态代码.