通常,最佳实践是创建一个与您想要接受的完全匹配的自定义对象。其原因之一是安全性。请参阅“过度发布”和“发布不足”:http
: //www.asp.net/web-api/overview/formats-and-model-binding/model-validation-in-aspnet-web-api这样您将创建一个仅包含您需要的属性的新对象。
public class ResponseBaseVM
{
public string ErrorReason { get; set; }
/*public bool IsRejected { get; set; }*/
}
public class ReadingVM : ResponseBaseVM
{
//Other properties that you only want available to user
}
然后你会接受 ReadingVM 的列表,但响应类型仍然是 typeof(reading)
[HttpPost]
[ValidationResponseFilter]
[Route("")]
[ResponseType(typeof(List<Reading>))] //will still display response with IsRejected
public IHttpActionResult Add(List<ReadingVM> readingListVM)
{
//Logic here
}
--- 解决方法 ---
同样,我认为您应该遵循上述方法。您要求解决问题,就在这里。在 HelpPageConfigurationExtensions.cs 类中找到您的“GenerateApiModel”方法并将其替换为:
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
//This will remove request body parameters from your Api Help Page matching 'IsRejected'
var isRejectedParameter = apiModel.RequestBodyParameters.SingleOrDefault(x => x.Name == "IsRejected");
if (isRejectedParameter != null)
apiModel.RequestBodyParameters.Remove(isRejectedParameter);
//This will remove elements with 'IsRejected' for the Help Page sample requests
var sampleRequests = new Dictionary<MediaTypeHeaderValue, object>();
foreach (var kvp in apiModel.SampleRequests)
{
//1.) iterate through each object in SampleRequests dictionary.
//2.) modify the json or xml to remove the "IsRejected" elements
//3.) assign modified results to a new dictionary
//4.) change the HelpPageApiModel. SampleRequests setter to be not private
//5.) assign new dictionary to HelpPageApiModel.SampleRequests
if (Equals(kvp.Key, new MediaTypeHeaderValue("application/json")))
{
var jObject = JObject.Parse(kvp.Value.ToString());
jObject.Remove("IsRejected");
sampleRequests.Add(new MediaTypeHeaderValue("application/Json"), jObject.ToString());
}
else if(Equals(kvp.Key, new MediaTypeHeaderValue("text/json")))
{
//do stuff
}
else if (Equals(kvp.Key, new MediaTypeHeaderValue("application/xml")))
{
//do stuff
}
else if (Equals(kvp.Key, new MediaTypeHeaderValue("text/xml")))
{
//do stuff
}
else
{
//form urlencoded or others
sampleRequests.Add(kvp.Key,kvp.Value);
}
}
apiModel.SampleRequests = sampleRequests;
return apiModel;
}
现在您可以看到“IsRejected”存在于响应中,但不存在于请求中。