0

是否可能出现以下情况:

创建一个消息处理程序来检查每个传入的请求。如果请求包含自定义标头键:“My-Header”并且其值为:“True”,则停止请求并向客户端返回自定义 json,否则,如果标头不存在或标头存在但值是“假”然后允许请求通过。

4

2 回答 2

0

我猜也许这会更好?

............

HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Forbidden);

var json = JsonConvert.SerializeObject(
                    new ErrorModel
                    {
                        Description = "error stuff",
                        Status = "Ooops"
                    });
response.Content = new StringContent(json);

var tcs = new TaskCompletionSource<HttpResponseMessage>();
tcs.SetResult(response);
return tcs.Task;
于 2013-10-23T22:11:02.060 回答
0

听起来你会按照下面显示的代码行做一些事情。这是假设您要发回的 JSON 将由ErrorModel此处表示。要将处理程序添加到 ASP.NET Web API 处理程序管道,请查看这篇关于如何连接的好文章。

public class MyHeaderHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request,
        CancellationToken cancellationToken)
    {
        string headerTokenValue;
        const string customHeaderKey = "My-Header";

        if (!request.Headers.TryGetValues(
                customHeaderKey,
                out headerTokenValue)
            || headerTokenValue.ToLower() != "true")
        {
            return base.SendAsync(request, cancellationToken);
        }

        return Task<HttpResponseMessage>.Factory.StartNew(
            () =>
                {
                    var response = new HttpResponseMessage(
                        HttpStatusCode.Unauthorized);
                    var json = JsonConvert.SerializeObject(
                        new ErrorModel
                        {
                            Description = "error stuff",
                            Status = "Ooops"
                        });
                    response.Content = new StringContent(json);
                    // Ensure return type is JSON:
                    response.Content.Headers.ContentType =
                       new MediaTypeHeaderValue("application/json");

                    return response;    
                });
    }
}
于 2013-10-23T16:15:26.273 回答