简体   繁体   中英

Web Api IHttpActionResult HttpContent

I want all my controllers calls to return a IHttpActionResult, so I made a class implementing this interface. When someone makes a GET call obviously some complex data is going to be sent back to the client inside this IHttpActionResult response object. Now I am having trouble inserting my content into my HttpResponseMessage. Here's what my error looks like when I make a call to one of my GET methods.

{"Message":"An error has occurred.","ExceptionMessage":"Cannot convert type 'XXXXX.DomainModels.News.AllNewsItems' to 'System.Net.Http.HttpContent'","ExceptionType":"Microsoft.CSharp.RuntimeBinder.RuntimeBinderException","StackTrace":" at CallSite.Target(Closure , CallSite , Object )
at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)
at XXXXAPI.PresentationLayer.Helpers.ActionResultGet.ExecuteAsync(CancellationToken cancellationToken) in

As you can see I am casting my content to HttpContent, that obviously is not doing the trick... And If I remove the cast I still get the same error. How do I get my complex type into this content?

public class ActionResultGet : IHttpActionResult
{
    private readonly HttpRequestMessage _request;
    private readonly dynamic _content;

    public ActionResultGet(HttpRequestMessage request, dynamic content)
    {
        _request = request;
        _content = content;
    }

    public Task<HttpResponseMessage> ExecuteAsync(
        System.Threading.CancellationToken cancellationToken)
    {
        if(_content == null)
        {
            var badResponse = new HttpResponseMessage()
            {
                StatusCode = HttpStatusCode.NotFound,
                Content = (HttpContent)this._content
            };

            return Task.FromResult(badResponse);
        }

        var response = new HttpResponseMessage()
        {
            StatusCode = HttpStatusCode.OK,
            Content = (HttpContent)this._content
        };

        return Task.FromResult(response);
    }
}

Regarding your issue, ideally you would need to supply an ObjectContent which accepts your data and also a content negotiated formatter.

But from your scenario above, you need not explicitly create a new type of action result here as by default Web API provides this functionality. For example, you can take a look at System.Web.Http.Results.NegotiatedContentResult<T> ...usually you wouldn't be using this type directly in your controller, but rather helpers like Ok<T> , StatusCode etc. Any controller which derives from ApiController get these helpers by default.

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