vb.net WebApi2 GET 上的 InvalidCastException 'HttpResponseMessage' 到 'IHttpActionResult'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25116032/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 17:57:18  来源:igfitidea点击:

InvalidCastException 'HttpResponseMessage' to 'IHttpActionResult' on WebApi2 GET

asp.netvb.netasp.net-web-api2

提问by EvilDr

Recently I've been following some WebApi2 tutorials. I have a situation whereby if a requested GET operation returns data outside of the user's remit, then I need to return a Forbidden code.

最近我一直在关注一些 WebApi2 教程。我有一种情况,如果请求的 GET 操作返回用户权限之外的数据,那么我需要返回一个禁止代码。

Imports System.Net
Imports System.Net.Http
Imports System.Web.Http

Namespace Controllers

    Public Class MyController
        Inherits ApiController

        <Route("Records/{id}")>
        Public Function [Get](id As Int32) As IHttpActionResult
            If Not Remit.IsWithinRemit(id) Then
                Return Request.CreateErrorResponse(HttpStatusCode.Forbidden, "This data is not within your remit")
            Else
                Dim r As New CustomObject(id)
                Return Ok(r)
            End If
        End Function

    End Class

End Namespace

Unfortunately, although the Ok(r)part works okay, CreateErrorResponsethrows an InvalidCastException:

不幸的是,虽然该Ok(r)部分工作正常,但CreateErrorResponse会抛出InvalidCastException

Unable to cast object of type 'System.Net.Http.HttpResponseMessage' to type 'System.Web.Http.IHttpActionResult'.

无法将“System.Net.Http.HttpResponseMessage”类型的对象转换为“System.Web.Http.IHttpActionResult”类型。

I know why the error is happening, but am unsure of the correct approach of how to fix it. In other threads, people advise that CreateErrorResponse()is the best approach for WebApi2, but VS creates it's sample GET request returning IHttpActionResult. Its like stuff doesn't seem to fit together for us newbies at the moment...

我知道错误发生的原因,但不确定如何修复它的正确方法。在其他线程中,人们建议这CreateErrorResponse()是 WebApi2 的最佳方法,但 VS 创建了它的示例 GET 请求返回IHttpActionResult。它就像现在似乎不适合我们这些新手的东西......

回答by toddmo

No, it isn't obvious, but you can get what you want (error code plus message) AND return it from a method of type IHttpActionResult. No need to change the return type or go without error messages.

不,这并不明显,但是您可以得到您想要的(错误代码加消息)并从 type 的方法中返回它IHttpActionResult。无需更改返回类型或没有错误消息。

This is the helper class:

这是助手类:

public class ErrorResult : IHttpActionResult
    {
        private HttpRequestMessage Request { get; }
        private HttpStatusCode statusCode;
        private string message;

        public ErrorResult(HttpRequestMessage request, HttpStatusCode statusCode, string message)
        {
            this.Request = request;
            this.statusCode = statusCode;
            this.message = message;
        }

        public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        {
            return Task.FromResult(Request.CreateErrorResponse(statusCode, message));
        }
    }

and you can call it like this:

你可以这样称呼它:

public IHttpActionResult MyMethod()
{
    MyServiceLayer myServiceLayer = new MyServiceLayer();
    MyType myvar;
    if (MyServiceLayer.EverythingIsOK(ref myvar))
        return Ok(myvar);
    else 
        return new ErrorResult(Request, HttpStatusCode.SomeErrorCode, "Something Is Wrong");
}

回答by malkam

try this

尝试这个

Change your Getmethod to return "HttpResponseMessage"

改变你的Get方法返回"HttpResponseMessage"

<Route("Records/{id}")>
Public Function [Get](id As Int32) As HttpResponseMessage
    If Not Remit.IsWithinRemit(id) Then
        Return Request.CreateResponse(HttpStatusCode.Forbidden, "This data is not within your remit")
    Else
        Dim r As New CustomObject(id)
        Return Request.CreateResponse(HttpStatusCode.OK, r)
    End If
End Function

Check below link

检查以下链接

http://www.asp.net/web-api/overview/web-api-routing-and-actions/action-results

http://www.asp.net/web-api/overview/web-api-routing-and-actions/action-results

回答by EvilDr

I found an alternative possiblesolution (there may be better but this one works and is simple). It returns

我找到了另一种可能的解决方案(可能有更好的解决方案,但这个可行且简单)。它返回

403 Forbidden

403 禁地

but with no content:

但没有内容:

<Route("Records/{id}")>
Public Function [Get](id As Int32) As IHttpActionResult
    If Not Remit.IsWithinRemit(id) Then
        Return New Results.StatusCodeResult(HttpStatusCode.Forbidden, Request)
    Else
        Dim r As New CustomObject(id)
        Return Ok(r)
    End If
End Function

Because HttpResponseMessagecomes from the same namespace, and also allows you to return custom error messages in addition to a HTTP status code, that option is more suitable to use in most cases.

因为HttpResponseMessage来自相同的命名空间,并且除了HTTP 状态代码之外还允许您返回自定义错误消息,因此该选项更适合在大多数情况下使用。

I guess IHttpActionResultis for basic status code returns with no frills. I posted this alongside the above answer to give new coders visibility of both options.

我猜IHttpActionResult是基本状态代码返回,没有多余的装饰。我将其与上述答案一起发布,以让新编码人员了解这两个选项。