开发者

Custom parameters handler in ASP.NET MVC

I have an action like this:

public JsonResult Action(String deviceId, Guid clien开发者_如何学PythontId)

So, according url (with parameters) will be like

www.site/ControllerName/Action?deviceId=123&clientId={some_guid}

There is no secret, that if it is impossible to parse {some_guid} into Guid type, asp.net will generate an error. The matter is in case of such wrong formatted requests I need the server to return special JSON result with message like { "result":"1"; "comments":"wrong url. review the parameter clientId" }.

How can I check action parameters before executing?


I would change your signature to:

public ActionResult Action(String deviceId, string clientId)

then you can

Guid id;
if (!Guid.TryParse(clientId, out id))
{
   // take appropiate action
}


I would keep what you had but make the parameters nullable;

public ActionResult Action(String deviceId, Guid? clientId)
{
     if (clientId.HasValue)
     {
         // Do something
     }
     else
     {
         throw new HttpException(404, "Url not found");
     }
 }

I realise this is almost the same as above, only here you are able to keep your types the same as your original post just checking to see if values have been passed


You probably want to use the ModelBinder for that and make the Guid.TryParse check there. If something has a wrong value, you can modify ModelState.

The second approach is to use somewhat special action filter attribute like that HandleErrorAttribute bundled with ASP.NET MVC. That filter could catch that particular type of exception and provide a specific error handling workflow and result substitution (probably the best idea here is just redirect to 404, because "wrong Guid" is nothing else but "non-existent page").


What I would do:

public ActionResult Action(int deviceId, string clientId)
{
    Guid clientGuid;

    if (!Guid.TryParse(clientId, out clientGuid))
    {
        throw new HttpException(404, "Action not found");
    }
    else
    {
        // Do some cool stuff....
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜