我的路线是:
public void RegisterRoute(HttpRouteCollection routes) {
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{guid}",
defaults: new { guid = RouteParameter.Optional }
);
}
Controller Action 就像
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.",
}
我正在尝试创建自定义模型绑定(bind)程序,但它不起作用
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;
}
}
请帮忙。如何只显示我的消息
最佳答案
您可以通过创建 Guid
来做到这一点一个Nullable<Guid>
并执行 null
检查:
public IHttpActionResult Get(Guid? guid) {
if(!guid.HasValue || guid.Value == Guid.Empty)
// return your error here
else
//...
}
关于c# - 验证 GUID 作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44762673/