簡體   English   中英

在Web Api中對GET請求使用JsonConverter

[英]Using JsonConverter on GET request in Web Api

我有一個具有JsonConverter屬性的抽象類,如下所示:

[JsonConverter(typeof(SurveyItemConverter))]
public abstract class SurveyItem:ISurveyItem
{
    private class SurveyItemConverter : JsonCreationConverter<ISurveyItem>
    {
        protected override ISurveyItem Create(Type objectType, Newtonsoft.Json.Linq.JObject jObject)
        {
            var type = (SurveyItemType)jObject.Value<int>("Type");

            switch (type)
            {
                case SurveyItemType.Label:
                    return new SurveyLabel();
                case SurveyItemType.Textbox:
                    return new SurveyTextbox();
                case SurveyItemType.TextArea:
                    return new SurveyTextArea();
                case SurveyItemType.CheckBoxGroup:
                    return new SurveyCheckboxGroup();
                case SurveyItemType.Checkbox:
                    return new SurveyCheckbox();
                case SurveyItemType.RadioGroup:
                    return new SurveyRadioGroup();
                case SurveyItemType.RadioButton:
                    return new SurveyRadioButton();
                case SurveyItemType.Email:
                    return new SurveyEmail();
                case SurveyItemType.Telephone:
                    return new SurveyTelephone();
                case SurveyItemType.Number:
                    return new SurveyNumber();
                case SurveyItemType.DateTime:
                    return new SurveyDate();
                case SurveyItemType.Password:
                    return new SurveyPassword();
                case SurveyItemType.Url:
                    return new SurveyUrl();
                case SurveyItemType.ProfileName:
                    return new SurveyProfileName();
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }
    }

    public string Label { get; set; }
    public int Id { get; set; }
    public SurveyItemType Type { get; set; }
}

如果該請求是POST / PUT,則可以正常工作,但是對於GET請求,它將失敗:

Cannot create an abstract class

處理get請求的控制器具有帶有簽名的方法(此方法用於不支持CORS的瀏覽器):

[HttpGet]
public async Task<IHttpActionResult> SubmitSurvey(HttpRequestMessage request, [FromUri] Survey survey)//survey contains a List<SurveyItem>

為什么不使用JsonConverter? 如何使JsonConverter與此方法配合使用?

Web API使用內容類型協商來確定要使用的反序列化器。 GET請求沒有正文,因此沒有內容類型。 Web API不會在URL中找到JSON,因此在這種情況下它不使用Json.Net,並且不會調用您的轉換器。 顯然,最好的選擇是使用POST,但是如果必須使它與GET一起使用,則您需要:

  • 發送數據作為標准查詢字符串參數(非JSON);
  • 從URL作為字符串獲取JSON並手動反序列化; 要么
  • 實現一個自定義綁定程序,該綁定程序知道要查找的內容並將其插入到Web API管道中

這是一個類似的問題 ,可能對前兩個選項有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM