如果找到自定义标头,ASP.NET Message Handler将返回json

时间:2013-10-23 09:54:48

标签: c# asp.net-web-api

是否可能出现以下情况:

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

2 个答案:

答案 0 :(得分:0)

听起来你会像下面的代码一样。这假设您要发回的JSON将由ErrorModel表示。要将处理程序添加到ASP.NET Web API处理程序管道,请查看this good article如何连接它。

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;    
                });
    }
}

答案 1 :(得分: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;