我的路由是:
public void RegisterRoute(HttpRouteCollection routes) {
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{guid}",
defaults: new { guid = RouteParameter.Optional }
);
}
控制器动作就像
public IHttpActionResult Get(Guid guid) {
当我通过api/{controller}/2ADEA345-7F7A-4313-87AE-F05E8B2DE678
时,一切正常,但是当我为guid传递无效值时
api/{controller}/xxxxxx
然后我收到错误:
{
"message": "The request is invalid.",
"messageDetail": "The parameters dictionary contains a null entry for parameter 'guid' of non-nullable type 'System.Guid' for method 'System.Web.Http.IHttpActionResult Get(System.Guid)' in 'Web.API.Controller.UserController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter."
}
如何显示我自己的消息:
{
"guid": "The value is invalid.",
}
我正在尝试创建自定义模型绑定器,但它无法正常工作
public class GuidModelBinder : IModelBinder {
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) {
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (value == null) {
bindingContext.ModelState.AddModelError("guid", "The value is invalid");
return false;
}
var result = Guid.TryParse(value.ToString(), out _);
if (!result) {
bindingContext.ModelState.AddModelError("guid", "The value is invalid");
}
return result;
}
}
请帮忙。我怎样才能只显示我的信息
答案 0 :(得分:3)
您可以通过public MappingJackson2HttpMessageConverter jacksonMessageConverter(){
MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
//authomatic registration
mapper.findAndRegisterModules();
messageConverter.setObjectMapper(mapper);
return messageConverter;
}
Guid
进行Nullable<Guid>
检查来完成此操作:
null
答案 1 :(得分:1)
关闭,但BindModel必须返回一个Guid。由于你的参数是一个guid,它是一个值类型,它必须有一个非null值。在下面的示例中,如果传入的值不是可解析的guid,我使用Guid.Empty作为值。
这将允许IIS使用Guid.Empty值和您指定的Model错误调用控制器。
public class GuidModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
Guid guidValue;
if (value == null || !Guid.TryParse(value.AttemptedValue, out guidValue))
{
bindingContext.ModelState.AddModelError("guid", "The value is invalid");
return Guid.Empty;
}
return guidValue;
}
}