本文介绍了创建新的IHttpActionResult操作结果方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法使用新的IHttpActionResult接口返回HttpStatusCode.NoContent响应消息?

Is there a way I can use the new IHttpActionResult interface to return a HttpStatusCode.NoContent response message?

我当前正在使用return new HttpResponseMessage( HttpStatusCode.NoContent );并希望将其转换为return NoContent();.

I am currently using return new HttpResponseMessage( HttpStatusCode.NoContent ); and would like to convert this into return NoContent();.

IHttpActionResult已经具有Ok()Conflict()NotFound(),但是我找不到在我的项目中需要使用的Forbidden()NoContent()中的任何一个.

IHttpActionResult has already got Ok(), Conflict() and NotFound() but I cannot find any for Forbidden() and NoContent() which I need to use in my project.

添加其他结果类型有多容易?

How easy is it to add other result types?

推荐答案

我发现了这个,其中显示了如何添加自定义IHttpActionResult方法,而我已经使用它创建了Forbidden()NoContent()方法,并取得了巨大的成功.

I found this example site that shows how to add a custom IHttpActionResult method and I've used this to create the Forbidden() and NoContent() methods with great success.

public abstract class CommonApiController : ApiController
{
    public class ForbiddenResult : IHttpActionResult
    {
        private readonly HttpRequestMessage _request;
        private readonly string _reason;

        public ForbiddenResult(HttpRequestMessage request,string reason)
        {
            _request = request;
            _reason = reason;
        }

        public ForbiddenResult(HttpRequestMessage request)
        {
            _request = request;
            _reason = "Forbidden";
        }

        public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        {
            var response = _request.CreateResponse(HttpStatusCode.Forbidden,_reason);
            return Task.FromResult(response);
        }
    }

    public class NoContentResult : IHttpActionResult
    {
        private readonly HttpRequestMessage _request;
        private readonly string _reason;

        public NoContentResult(HttpRequestMessage request,string reason)
        {
            _request = request;
            _reason = reason;
        }

        public NoContentResult(HttpRequestMessage request)
        {
            _request = request;
            _reason = "No Content";
        }

        public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        {
            var response = _request.CreateResponse(HttpStatusCode.NoContent,_reason);
            return Task.FromResult(response);
        }
    }
}

然后我可以像这样使用它:

And then I can use it like this:

public class InvoiceController : CommonApiController
{
    public async Task<IHttpActionResult> Post([FromBody]Invoice invoice)
    {
        if(User.IsInRole("Readonly"))
        {
            return Forbidden();
        }

        // Rest of code

    }
}

这篇关于创建新的IHttpActionResult操作结果方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 06:14