0

当提交被推送到存储库(接收后挂钩)时,github 可以提醒您并调用您的 Web 服务。github 将提交信息作为 JSON 发送,但在表单编码参数中。即内容类型为application/x-www-form-urlencoded,http请求为

POST /my_uri HTTP/1.1
Content-Type: application/x-www-form-urlencoded

payload=%7B%22ref%22%3A%22refs%2Fheads...

我想编写处理 ASP.NET MVC 或 WebAPI 中的新提交的 web 服务。我已经定义了一些类来反序列化 json,但我无法让框架直接初始化我的对象。我现在拥有的是

public string my_uri(string payload)
{
    var s = new JavaScriptSerializer();
    var p = s.Deserialize(payload, typeof(Payload)) as Payload;
    ...
}

但我想要

public string my_uri(Payload payload)
{
    ...
}

我已经阅读了有关 ValueProviders 的信息,但我没有找到链接它们的方法。我需要编写 FormValueProviderFactory 和 JsonValueProviderFactory。如何让 ASP 进行绑定?

4

1 回答 1

1

首先,我有点困惑为什么他们会将 Json 数据填充到表单编码的正文数据中。如果一个服务最终可以理解 Json(因为它必须反序列化它),为什么不发布为“application/json”本身呢?他们这样做是因为CORS吗?

除此之外,您可以创建一个自定义参数绑定,如下所示,看看它是否符合您的需求:

行动

public Payload Post([PayloadParamBinding]Payload payload)

自定义参数绑定

public class PayloadParamBindingAttribute : ParameterBindingAttribute
{
    public override HttpParameterBinding GetBinding(HttpParameterDescriptor parameter)
    {
        return new PayloadParamBinding(parameter);
    }
}

public class PayloadParamBinding : HttpParameterBinding
{
    HttpParameterBinding _defaultFormatterBinding;

    public PayloadParamBinding(HttpParameterDescriptor desc)
        :base(desc)
    {
        _defaultFormatterBinding = new FromBodyAttribute().GetBinding(desc);
    }

    public override async Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken)
    {
        if (actionContext.Request.Content != null)
        {
            NameValueCollection nvc = await actionContext.Request.Content.ReadAsFormDataAsync();

            StringContent sc = new StringContent(nvc["payload"]);
            //set the header so that Json formatter comes into picture
            sc.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            actionContext.Request.Content = sc;

            //Doing like this here because we want to simulate the default behavior of when a request
            //is posted as Json and the Json formatter would have been picked up and also the model validation is done.
            //This way you are simulating the experience as of a normal "application/json" post request.
            await _defaultFormatterBinding.ExecuteBindingAsync(metadataProvider, actionContext, cancellationToken);
        }
    }

    public override bool WillReadBody
    {
        get
        {
            return true;
        }
    }
}
于 2013-06-28T19:27:26.823 回答