如何使用Forbidden状态web api返回ModelState

时间:2017-09-04 08:06:42

标签: c# asp.net-web-api serialization modelstate modelstatedictionary

我们可以通过以下方式从网络API返回ModelState BadRequest

return BadRequest(ModelState);

它提供以下输出:

{
    "Message": "The request is invalid.",
    "ModelState": {
        "property": [
            "error"
        ]
    }
}

如何以Forbidden状态返回相同的输出?

我尝试了以下方法:

return Content(HttpStatusCode.Forbidden, ModelState);

但它返回:

{
    "property": {
        "_errors": [
            {
                "<Exception>k__BackingField": null,
                "<ErrorMessage>k__BackingField": "error"
            }
        ],
        "<Value>k__BackingField": null
    }
}

Json序列化ModelSate也没有返回相同的东西。如何将BadRequest() ModelState方法使用的序列化方法与其他状态代码一起使用?

1 个答案:

答案 0 :(得分:0)

您可以使用ExecuteAsync InvalidModelStateResult BadRequest() ApiController方法的ModelState方法的InvalidModelStateResult方法实现所需的输出,该方法实际序列化了ExecuteAsync

因此,我们的想法是创建一个扩展public class ModelStateResult : InvalidModelStateResult { private readonly HttpStatusCode _status; public ModelStateResult(ModelStateDictionary modelState, ApiController controller, HttpStatusCode status) : base(modelState, controller) { _status = status; } public override Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) { var response = base.ExecuteAsync(cancellationToken).Result; response.StatusCode = _status; return Task.FromResult(response); } } 并覆盖return new ModelStateResult(ModelState, this, HttpStatusCode.Forbidden); //this refers to ApiController here 方法的新类来更改状态代码。

InvalidModelStateResult

使用它像:

public class ModelStateResult : IHttpActionResult
{
    public HttpStatusCode Status { get; }
    public ModelStateDictionary ModelState { get; }
    public HttpRequestMessage Request { get; }

    public ModelStateResult(HttpStatusCode status, ModelStateDictionary modelState, HttpRequestMessage request)
    {
        Status = status;
        ModelState = modelState;
        Request = request;
    }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var response = Request.CreateErrorResponse(Status, ModelState);
        return Task.FromResult(response);
    }
}

我认为这只是一种解决方法,希望有人发布更好的方法来实现它。

修改

不使用function curl_delete($url) { $ch = curl_init(); curl_setopt_array($ch, [ CURLOPT_CUSTOMREQUEST => 'DELETE', CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true ]); $response = curl_exec($ch); curl_close($ch); return $response; } function curl_put($url, $data) { $ch = curl_init(); curl_setopt_array($ch, [ CURLOPT_CUSTOMREQUEST => 'PUT', CURLOPT_URL => $url, CURLOPT_HTTPHEADER => [ 'Content-Type: application/json', 'Content-Length: ' . strlen($data), ], CURLOPT_POSTFIELDS => $data, CURLOPT_RETURNTRANSFER => true ]); $response = curl_exec($ch); curl_close($ch); return $response; } function curl_post($url, $data) { $ch = curl_init(); curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_URL => $url, CURLOPT_HTTPHEADER => ['Content-Type: application/json'], CURLOPT_POSTFIELDS => $data, CURLOPT_RETURNTRANSFER => true ]); $response = curl_exec($ch); curl_close($ch); return $response; } echo curl_delete('localhost:9200/my_index?pretty'); echo curl_put('localhost:9200/my_index?pretty', '{"settings": {"number_of_shards": 1}}'); echo curl_post('localhost:9200/my_index/my_type/_bulk?pretty', ' { "index": { "_id": 1 }} { "title": "The quick brown fox" } { "index": { "_id": 2 }} { "title": "The quick brown fox jumps over the lazy dog" } { "index": { "_id": 3 }} { "title": "The quick brown fox jumps over the quick dog" } { "index": { "_id": 4 }} { "title": "Brown fox brown dog" } '); echo curl_post('localhost:9200/my_index/my_type/_refresh?pretty', '{}'); echo curl_post('localhost:9200/my_index/my_type/_search?pretty', '{}');

{
  "acknowledged" : true
}
{
  "acknowledged" : true,
  "shards_acknowledged" : true
}
{
  "took" : 92,
  "errors" : false,
  "items" : [
    {
      "index" : {
        "_index" : "my_index",
        "_type" : "my_type",
        "_id" : "1",
        "_version" : 1,
        "result" : "created",
        "_shards" : {
          "total" : 2,
          "successful" : 1,
          "failed" : 0
        },
        "created" : true,
        "status" : 201
      }
    },
    {
      "index" : {
        "_index" : "my_index",
        "_type" : "my_type",
        "_id" : "2",
        "_version" : 1,
        "result" : "created",
        "_shards" : {
          "total" : 2,
          "successful" : 1,
          "failed" : 0
        },
        "created" : true,
        "status" : 201
      }
    },
    {
      "index" : {
        "_index" : "my_index",
        "_type" : "my_type",
        "_id" : "3",
        "_version" : 1,
        "result" : "created",
        "_shards" : {
          "total" : 2,
          "successful" : 1,
          "failed" : 0
        },
        "created" : true,
        "status" : 201
      }
    },
    {
      "index" : {
        "_index" : "my_index",
        "_type" : "my_type",
        "_id" : "4",
        "_version" : 1,
        "result" : "created",
        "_shards" : {
          "total" : 2,
          "successful" : 1,
          "failed" : 0
        },
        "created" : true,
        "status" : 201
      }
    }
  ]
}
{
  "_index" : "my_index",
  "_type" : "my_type",
  "_id" : "_refresh",
  "_version" : 1,
  "result" : "created",
  "_shards" : {
    "total" : 2,
    "successful" : 1,
    "failed" : 0
  },
  "created" : true
}
{
  "took" : 2,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "failed" : 0
  },
  "hits" : {
    "total" : 0,
    "max_score" : null,
    "hits" : [ ]
  }
}