ASP.. NET Web API PUT动作参数不执行

本文关键字:参数 执行 PUT NET Web API ASP | 更新日期: 2023-09-27 17:50:53

好的,我有一个MediaTypeFormatter:

public class iOSDeviceXmlFormatter : BufferedMediaTypeFormatter
{
    public iOSDeviceXmlFormatter() {
        SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/xml"));
        SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/xml"));
    }
    public override bool CanReadType(Type type) {
        if (type == typeof(iOSDevice)) {
            return true;
        }
        return false;
    }
    public override object ReadFromStream(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger) {
        iOSDevice device = null;
        using (XmlReader reader = XmlReader.Create(readStream)) {
            if (reader.ReadToFollowing("iOSDevice")) {
                if (!reader.IsEmptyElement) {
                    device = new iOSDevice();
                    ... do processing here ...
                }
            }
        }
        readStream.Close();
        return device;
    }
我有这个操作来处理PUT:
    public void Put(string id, iOSDevice model)
    {
    }

我也试过了:

    public void Put(string id, [FromBody]iOSDevice model)
    {
    }

我试过了:

    public void Put(string id, [FromBody]string value)
    {
    }

当我这样做时,这些都不起作用:

string data = "<iOSDevice>xml_goes_here</iOSDevice>";
WebClient client = new WebClient();
client.UploadString(url, "PUT", data);

动作拒绝触发我的iOSDeviceXmlFormatter,它甚至不会读取它作为一个[FromBody]字符串。你怎么让这个东西映射?

谢谢,Allison

ASP.. NET Web API PUT动作参数不执行

您是如何注册格式化程序的?您需要在第一个位置注册这个格式化程序,以便它优先于WebAPI的默认格式化程序。代码看起来像这样:

config.Formatters.Insert(0, new iOSDeviceXmlFormatter());

这应该确保任何以内容类型application/xml或类型iOSDevice的text/xml进入的请求使用你的格式化器进行反序列化

您已经指定您的格式化程序将为以下请求触发Content-Type标头:

SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/xml"));
SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/xml"));

但是您没有在请求中设置它们。这就是自定义格式化程序永远不会被触发的原因。所以一旦你在全局配置中注册了它:

config.Formatters.Insert(0, new iOSDeviceXmlFormatter());

您应该确保您设置了正确的请求Content-Type标头:

string data = "<iOSDevice>xml_goes_here</iOSDevice>";
using (WebClient client = new WebClient())
{
    // That's the important part that you are missing in your request
    client.Headers[HttpRequestHeader.ContentType] = "text/xml";
    var result = client.UploadString(url, "PUT", data);
}

现在将触发以下动作:

public void Put(string id, iOSDevice model)
{
}

和你的自定义格式化程序将被调用之前,为了从请求实例化你的iOSDevice